php preg_replace replacement failure solution: first open the corresponding PHP code file; then print out the ASCII code for the characters that cannot be replaced and replace them.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
php preg_replace space cannot be replaced problem
A small bug that cheats me. Read a piece of text (encoded utf-8) and want to replace spaces. Neither str_replace(" "..) nor preg_replace("/\s/"..) works.
你好'; $str = preg_replace('/\s/is','',$c); $str = str_replace(" ", "a", $str); var_dump($str); //不起作用
There is no way, I saw it after ord() the space that cannot be replaced. This utf-8 space is special. ASCII 194 160 comes out.
你好'; $str = str_replace(chr(194) . chr(160), "a", $str); // 解决方法1 $str = preg_replace('/\xC2\xA0/is', "a", $str); // 解决方法2 var_dump($str); //ok
The root of the problem is that there is a special character in UTF-8 encoding, and its encoding is "0xC2 0xA0" (194 160). When converted into characters, it appears as a space, which is the same as a normal half-width space (ASCII 0x20). The only difference is that its width will not be compressed, so it is often used for web page layout (such as first line indentation). kind). Other encoding methods such as GB2312 and Unicode do not have such characters.
Sort out the various characters that cannot be replaced:
chr(194).chr(160) 变现为空格 chr(227).chr(128) 变现为空格 chr(226).chr(128).chr(172).chr(226).chr(128).chr(172).chr(30) 变现为空
Summary: For characters that cannot be replaced, you can always print out the ASCII code Replace it.
[Recommended learning: "PHP Video Tutorial"]
The above is the detailed content of What should I do if php preg_replace fails?. For more information, please follow other related articles on the PHP Chinese website!