Home >Backend Development >PHP Problem >What should I do if php preg_replace fails?

What should I do if php preg_replace fails?

藏色散人
藏色散人Original
2021-03-05 10:23:212220browse

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.

What should I do if php preg_replace fails?

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.

 <?php
 
 $str = &#39;<p>    你好<p>&#39;;
 $str = preg_replace(&#39;/\s/is&#39;,&#39;&#39;,$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.

 <?php
 
 $str = &#39;<p>    你好<p>&#39;;
 $str = str_replace(chr(194) . chr(160), "a", $str);  // 解决方法1
 $str = preg_replace(&#39;/\xC2\xA0/is&#39;, "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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn