What should I do if php preg_replace fails?

藏色散人
Release: 2023-03-08 13:20:01
Original
2099 people have browsed it

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.

 你好

'; $str = preg_replace('/\s/is','',$c); $str = str_replace(" ", "a", $str); var_dump($str); //不起作用

Copy after login

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

Copy after login

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) 变现为空
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!