Delete spaces php - php

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.

Solution of this problem
$str = trim($str, chr(0xC2).chr(0xA0))

You should use preg_replace(), to make it in multibyte-safe way.
$str = preg_replace('/^[\s\x00]+|[\s\x00]+$/u', '', $str);
Notes:
this will fix initial #Андрей-Сердюк's problem: it will trim \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 behavior
Accepted #Андрей-Сердюк 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à"

How about:
$string = '" Adv "';
$noSpace = preg_replace('/\s/', '', $string);
?
http://php.net/manual/en/function.preg-replace.php

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).

$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 .']';

Related

Find last word of a string that has special characters

I am trying to add a span tag to the last word of a string. It works if the string has no special characters. I can't figure out the correct regex for it.
$string = "Onun Mesajı";
echo preg_replace("~\W\w+\s*\S?$~", ' <span>' . '\\0' . '</span>', $string);
Here is the Turkish character set : ÇŞĞÜÖİçşğüöı
You need to use /u modifier to allow processing Unicode characters in the pattern and input string.
preg_replace('~\w+\s*$~u', '<span>$0</span>', $string);
^
Full PHP demo:
$string = "Onun Mesajı";
echo preg_replace("~\w+\s*$~u", '<span>$0</span>', $string);
Also, the regex you need is just \w+\s*$:
\w+ - 1 or more alphanumerics
\s* - 0 or more whitespace (trailing)
$ - end of string
Since I removed the \W from the regex, there is no need to "hardcode" the leading space in the replacement string (removed, too).
You should use the u modifier for regular expressions to set the engine into unicode mode:
<?php
$subject = "Onun äöüß Mesajı";
$pattern = '/\w+\s*?$/u';
echo preg_replace($pattern, '<span>\\0</span>', $subject);
The output is:
Onun äöüß <span>Mesajı</span>
This regex will do the trick for you, and is a lot shorter then the other solutions:
[ ](.*?$)
Here is an example of it:
$string = "Onun Mes*ÇŞĞÜÖİçşğüöıajı";
echo preg_replace('~[ ](.*?$)~', ' <span>' .'${1}'. '</span>', $string);
Will echo out:
Onun <span>Mes*ÇŞĞÜÖİçşğüöıajı</span>
The way this regex works is that we look for any characters without space in lazy mode [ ].*?.
then we add the $ identifier, so it matches from the end of the string instead.

non-breaking utf-8 0xc2a0 space and preg_replace strange behaviour

In my string I have utf-8 non-breaking space (0xc2a0) and I want to replace it with something else.
When I use
$str=preg_replace('~\xc2\xa0~', 'X', $str);
it works OK.
But when I use
$str=preg_replace('~\x{C2A0}~siu', 'W', $str);
non-breaking space is not found (and replaced).
Why? What is wrong with second regexp?
The format \x{C2A0} is correct, also I used u flag.
Actually the documentation about escape sequences in PHP is wrong. When you use \xc2\xa0 syntax, it searches for UTF-8 character. But with \x{c2a0} syntax, it tries to convert the Unicode sequence to UTF-8 encoded character.
A non breaking space is U+00A0 (Unicode) but encoded as C2A0 in UTF-8. So if you try with the pattern ~\x{00a0}~siu, it will work as expected.
I've aggegate previous answers so people can just copy / paste following code to choose their favorite method :
$some_text_with_non_breaking_spaces = "some text with 2 non breaking spaces at the beginning";
echo 'Qty non-breaking space : ' . substr_count($some_text_with_non_breaking_spaces, "\xc2\xa0") . '<br>';
echo $some_text_with_non_breaking_spaces . '<br>';
# Method 1 : regular expression
$clean_text = preg_replace('~\x{00a0}~siu', ' ', $some_text_with_non_breaking_spaces);
# Method 2 : convert to bin -> replace -> convert to hex
$clean_text = hex2bin(str_replace('c2a0', '20', bin2hex($some_text_with_non_breaking_spaces)));
# Method 3 : my favorite
$clean_text = str_replace("\xc2\xa0", " ", $some_text_with_non_breaking_spaces);
echo 'Qty non-breaking space : ' . substr_count($clean_text, "\xc2\xa0"). '<br>';
echo $clean_text . '<br>';
The two codes do different things in my opinion: the first \xc2\xa0 will replace TWO characters, \xc2 and \xa0 with nothing.
In UTF-8 encoding, this happens to be the codepoint for U+00A0.
Does \x{00A0} work? This should be the representation for \xc2\xa0.
I did not work this variant ~\x{c2a0}~siu.
Varian \x{00A0} works. I have not tried the second option and here is the result:
I tried to convert it to hex and replace no-break space 0xC2 0xA0 (c2a0) to space 0x20 (20).
Code:
$hex = bin2hex($item);
$_item = str_replace('c2a0', '20', $hex);
$item = hex2bin($_item);
/\x{00A0}/, /\xC2\xA0/ and $clean_hex2bin-str_replace-bin2hex worked and didn't work. If I printed it out to the screen, it's all good, but if I tried to save it to a file, the file would be blank!
I ended up using iconv('UTF-8', 'ISO-8859-1//IGNORE', $str);

Why is my attempt to replace a character in a string failing?

I have a string (taken from a MySQL database if it makes any difference) which looks normal enough:
Manufacture: Blah
The problem is that the space between Manufacture: and the <a> tag has a charcode of 194, not 32 as I would expect.
This is causing a preg_match with the following pattern to fail (please ignore the attempts to parse HTML with regex, I know it's not a good idea but this particular dataset is predictable enough to get away with it):
/Manufacture: *(<a[^>]*>([A-Za-z- 0-9]+)<\/a>)/i
If I replace the rogue space with a normal space character in a text editor and try again, the expression matches as expected, but I need to alter it programatically.
I tried str_replace:
$text = str_replace(chr(194), ' ', $text);
But the preg_match still fails. I then tried preg_replace:
$text = preg_replace('/[\xC2]/', ' ', $text);
But that doesn't work either, even though running that same pattern through preg_match does contain the expected match.
Does anyone have any ideas?
Can you please check the structure of the MySQL table where you get the contents of $text from? If the collation is utf8_general_ci or something like that then your string most likely contains a double-byte UNICODE character.
If that is the case then the PHP function iconv should do the trick. Here's the example from the PHP manual. The IGNORE option should remove the UNICODE character from the string.
<?php
$text = "This is the Euro symbol '€'.";
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;
?>
The above example will output something similar to:
Original : This is the Euro symbol '€'.
TRANSLIT : This is the Euro symbol 'EUR'.
IGNORE : This is the Euro symbol ''.
Plain :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
This is the Euro symbol '
what if you try to match any whitespace character?
like so:
/Manufacture:\s*(<a[^>]*>([A-Za-z- 0-9]+)<\/a>)/i

Remove HTML codes from string in PHP

I want to remove all HTML codes like " € á ... from a string using REGEX.
String: "This is a string " € á &"
Output Required: This is a string
you can try
$str="This is a string " € á &";
$new_str = preg_replace("/&#?[a-z0-9]+;/i",'',$str);
echo $new_str;
i hope this may work
DESC:
& - starting with
# - some HTML entities use the # sign
?[a-z0-9] - followed by
;- ending with a semi-colon
i - case insensitive.
If you're trying to totally remove entities (ie: not decoding them) then try this:
$string = 'This is a string " € á &';
$pattern = '/&([#0-9A-Za-z]+);/';
echo preg_replace($pattern, '', $string);
$str = preg_replace_callback('/&[^; ]+;/', function($matches){
return html_entity_decode($matches[0], ENT_QUOTES) == $matches[0] ? $matches[0] : '';
}, $str);
This will work, but won't strip € since that is not an entity in HTML 4. If you have PHP 5.4 you can use the flags ENT_QUOTES | ENT_HTML5 to have it work correctly with HTML5 entities like €.
preg_replace('#&[^;]+;#', '', "This is a string " € á &");
Try this:
preg_replace('/[^\w\d\s]*/', '', htmlspecialchars_decode($string));
Although it might remove some things you don't want removed. You may need to modify the regex.

php removing excess whitespace

I'm trying to remove excess whitespace from a string like this:
hello world
to
hello world
Anyone has any idea how to do that in PHP?
With a regexp :
preg_replace('/( )+/', ' ', $string);
If you also want to remove every multi-white characters, you can use \s (\s is white characters)
preg_replace('/(\s)+/', ' ', $string);
$str = 'Why do I
have so much white space?';
$str = preg_replace('/\s{2,}/', ' ', $str);
var_dump($str); // string(34) "Why do I have so much white space?"
See it!
You could also use the + quantifier, because it always replaces it with a . However, I find {2,} to show your intent clearer.
There is an example on how to strip excess whitespace in the preg_replace documentation
Not a PHP expert, but his sounds like a job for REGEX....
<?php
$string = 'Hello World and Everybody!';
$pattern = '/\s+/g';
$replacement = ' ';
echo preg_replace($pattern, $replacement, $string);
?>
Again, PHP is not my language, but the idea is to replace multiple whitespaces with single spaces. The \s stands for white space, and the + means one or more. The g on the end means to do it globally (i.e. more than once).

Categories