php / php-src

The PHP Interpreter
https://www.php.net
Other
38.15k stars 7.74k forks source link

preg_replace错误 #16607

Closed soitif closed 5 hours ago

soitif commented 5 hours ago

Description

The following code:

<?php
// 替换字符串内的逗号、中文逗号、分号、顿号、空格等为英文逗号,会发生部分中文字符乱码
$str = "我发送到发顺丰,,阿斯蒂芬去玩了,,发生、的吴  青峰";
$newStr = preg_replace('/[,,;、\s]+/', ',', $str);
echo $newStr;

Resulted in this output:

我发�,到发顺丰,阿斯蒂芬去玩了,发生,的吴,青峰

But I expected this output instead:

我发送到发顺丰,阿斯蒂芬去玩了,发生,的吴,青峰

PHP Version

PHP 8.3.3

Operating System

Mac

damianwadley commented 5 hours ago

You need the /u flag when working with UTF-8 strings.

https://www.php.net/manual/zh/reference.pcre.pattern.modifiers.php

u (PCREUTF8) 这个修饰符打开了 PCRE 的额外功能,这些功能与 Perl 不兼容。模式和主题字符串被视为 UTF-8。 无效的主题字符串会导致 preg* 函数匹配不到任何内容;无效的模式会触发一个 E_WARNING 级别的错误。 五个和六个字节的 UTF-8 序列被视为无效。

$newStr = preg_replace('/[,,;、\s]+/u', ',', $str);
我发送到发顺丰,阿斯蒂芬去玩了,发生,的吴,青峰

https://3v4l.org/l0Oh4