直截了当的问题;我怎样才能将以下两个preg_replace模式合并为一个?将两个preg_replace模式组合成一个
preg_replace('/(?<!\d)[.,!?](?![.,!?\d])/', '$0 ', $filecontent);
preg_replace('/\s\s+/', ' ', $filecontent);
第一个来自this answer,而第二个简单地删除过量使用的空间。
我试图做一些什么链(见下面注释的线),但没有奏效 - 也不会是我想的最好的解决方案。
$fp2 = fopen($filepath, 'r+');
$filecontent = file_get_contents($filepath);
$correctedpunctation = preg_replace('/(?<!\d)[.,!?](?![.,!?\d])/', '$0 ', $filecontent);
/* $correctedspacing = preg_replace('/\s\s+/', ' ', $correctedpunctation); */
/* fwrite($fp2, $correctedpunctation); */
fwrite($fp2, $correctedpunctation);
fclose($fp2);
我一直试图在regular expressions读了,但我不知道如何使用这种字符替换,并找到模式相当困难的阅读和理解。我似乎无法将它们添加到一起,而不会破坏此preg_replace的某些或所有预期功能。任何解释和/或例子将非常感激。
如果他们都做完全不同的东西那么就应该是没有问题让他们分开。只是想知道为什么你想要结合他们。另外,你可能会在前面添加'\ s'来防止在标点后面加空格。例如:'...(?![。,!?\ d \ s])' – 2015-02-10 18:16:48