PHP preg_match/replace不支持字符"ndash"在函数


PHP preg_match/replace doesn't work on character "ndash" after file_get_contents

我通过file_get_contents($file)得到一个字符串。

为什么我不能用PHP的preg_replace函数替换"-"(不是"minus",而是HTML –) ?Preg_match也不工作:

$file的输出为"blah - blah"。

$str = file_get_contents($file); $str = preg_replace('/–/', 'test', $str); echo $str;

应该返回blah test blah,但是返回blah – blah

那是什么,我怎么能代替一个破折号呢?

谢谢你的帮助!

似乎该文件包含一个HTML实体的长横线,为了获得纯文本与你需要使用html_entity_decode首先。

使用

$str = preg_replace('/–/', 'test', html_entity_decode($str));
                                   ^^^^^^^^^^^^^^^^^^^^^^^^
PHP演示:

$str = 'blah – blah';
echo "Original: " . $str . "'n";
$str = preg_replace('/–/', 'test', html_entity_decode($str));
echo "Replaced: " .  $str;
输出:

Original: blah – blah
Replaced: blah test blah