Reputation: 600
I need delete all tags from string and make it without spaces.
I have string
"<span class="left_corner"> </span><span class="text">Adv</span><span class="right_corner"> </span>"
After using strip_tags I get string
" Adv "
Using trim function I can`t delete spaces.
JSON string looks like "\u00a0...\u00a0".
Help me please delete this spaces.
Upvotes: 1
Views: 4247
Reputation: 1
I was using the accepted solution for years and I've been wrong all this time. If I can find this solution in 2022, others too, so please change the accepted solution to the one from @e1v who was right all this time.
You SHOULD NOT DO THIS!
echo trim('Au delà', ' '.chr(0xC2).chr(0xA0));
As it corrupts the UTF-8 encoding:
Au del�
Note that a "modern" (PHP 7) way to write this could be:
echo trim('Au delà', " \u{a0}");//This is WRONG, don't do it!
Personally, when I have to deal with non breakable spaces (Unicode 00A0, UTF8 C2A0) in strings, I replace the trailing/ending ones by regular spaces (Unicode 0020, UTF8 20), and then trim the string. Like this:
echo trim(preg_replace('/^\s+|\s+$/u', ' ', "Au delà\u{a0}"));
(I would have post a comment or just vote the answer up, but I can't).
Upvotes: 0
Reputation: 637
You should use preg_replace()
, to make it in multibyte-safe way.
$str = preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', $str);
Notes:
\u00a0
, because \s
matches Unicode non-breaking spaces too/u
modifier (PCRE_UTF8) tells PCRE to handle subject as UTF8-string\x00
matches null-byte characters to mimic default trim()
function behaviorAccepted @Андрей-Сердюк trim()
answer will mess with multibyte strings.
Example:
// This works:
echo trim(' Hello ', ' '.chr(0xC2).chr(0xA0));
// > "Hello"
// And this doesn't work:
echo trim(' Solidarietà ', ' '.chr(0xC2).chr(0xA0));
// > "Solidariet?" -- invalid UTF8 character sequense
// This works for both single-byte and multi-byte sequenses:
echo preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', ' Hello ');
// > "Hello"
echo preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', ' Solidarietà ');
// > "Solidarietà"
Upvotes: 4
Reputation: 600
Solution of this problem
$str = trim($str, chr(0xC2).chr(0xA0))
Upvotes: 7
Reputation: 982
$str = '<span class="left_corner"> </span><span class="text">Adv</span><span class="right_corner"> </span>';
$rgx = '#(<[^>]+>)|(\s+)#';
$cleaned_str = preg_replace( $rgx, '' , $str );
echo '['. $cleaned_str .']';
Upvotes: -1
Reputation: 139
How about:
$string = '" Adv "';
$noSpace = preg_replace('/\s/', '', $string);
?
http://php.net/manual/en/function.preg-replace.php
Upvotes: 0