How can I remove the ETX character (0x03) from the end of a string? I'd either like a function, otherwise I can write a regular expression, all I wan开发者_运维百科t to know is how to match the ETX character in a regular expression? trim()
doesn't work.
To complete Charles' answer, I had a case where the ETX character was not at the end of the line so I had to use the following code:
$string = preg_replace('/\x03/', '', $string);
Just remove the $ sign.
Have you tried rtrim function
http://php.net/manual/en/function.rtrim.php
The ETX is a control character, which means we have to go through some extra effort to bring it into existence.
From the PHP interactive prompt:
php > $borked = "Hello, have an ETX:" . chr(3);
php > print_r($borked);
Hello, have an ETX:
php > var_export($borked);
'Hello, have an ETX:'
php > echo urlencode($borked);
Hello%2C+have+an+ETX%3A%03
php > var_dump( preg_match('/' . chr(3) . '/', $borked) );
int(1)
php > var_dump( preg_match('/' . chr(3) . '$/', $borked) );
int(1)
php > echo urlencode( preg_replace('/' . chr(3) . '$/', '', $borked) );
Hello%2C+have+an+ETX%3A
In other words, you can basically just inject the character into the regex string. Now, this might backfire. This technique may backfire based on character sets and other horrible things.
In addition to chr(3)
, you could also try urldecode('%03')
to produce the character. You can also use a special escape syntax, as listed on the PCRE syntax pages: /\x03$/
Here's a function for you, using that last method:
function strip_etx_at_end_of_string($string) {
return preg_replace('/\x03$/', '', $string);
}
At a guess rtrim($var,"\c"); or preg_replace("/\c+\$/",'',$var);
精彩评论