[英]How to replace all spaces which are not actually spaces with regex in PHP
I have the following string which I want to 'clean' from multiple whitespaces: 我有以下要从多个空格“清除”的字符串:
$string = "This is a test string"; //Using utf8_decode
Not a big deal right? 没什么大不了的吗? However, the string is not 'cleaned' after using: 但是,在使用以下字符串后,该字符串不会被“清除”:
$string = preg_replace('/\s+/', ' ', $string);
Because, the string actually is like this: 因为,字符串实际上是这样的:
$test = "This is a  test string";
So, how can I fix this issue? 那么,如何解决此问题?
Thanks. 谢谢。
Please, I don't want to replace the  character like str_replace('Â', '')
or something 拜托,我不想替换诸如str_replace('Â', '')
类的Â字符
You may use the /u
UNICODE modifier: 您可以使用/u
UNICODE修饰符:
$string = preg_replace('/\s+/u', ' ', $string);
The
/u
modifier enables the PCRE engine to handle strings as UTF8 strings (by turning onPCRE_UTF8
verb) and make the shorthand character classes in the pattern Unicode aware (by enablingPCRE_UCP
verb)/u
修饰符使PCRE引擎能够将字符串作为UTF8字符串处理(通过打开PCRE_UTF8
动词),并使模式中的速记字符类能够PCRE_UCP
Unicode(通过启用PCRE_UCP
动词)
The main point is that \\s
will now match all Unicode whitespace and the input string is treated as a Unicode string. 要点是\\s
现在将匹配所有Unicode空格,并且输入字符串被视为Unicode字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.