将两个 preg_replace 模式合并为一个
Combining two preg_replace patterns into one
直截了当的问题;如何将以下两个 preg_replace 模式合并为一个?
preg_replace( '/(?<!\d)[.,!?](?![.,!?\d])/', '[=11=] ', $filecontent);
preg_replace('/\s\s+/', ' ', $filecontent);
第一个来自this answer,而第二个简单地删除了过多的空格。
我尝试对链进行一些操作(请参阅下面注释掉的行),但这没有用——而且我认为这也不是最好的解决方案。
$fp2 = fopen($filepath, 'r+');
$filecontent = file_get_contents($filepath);
$correctedpunctation = preg_replace( '/(?<!\d)[.,!?](?![.,!?\d])/', '[=12=] ', $filecontent);
/* $correctedspacing = preg_replace('/\s\s+/', ' ', $correctedpunctation); */
/* fwrite($fp2, $correctedpunctation); */
fwrite($fp2, $correctedpunctation);
fclose($fp2);
我一直在努力阅读 regular expressions,但我不熟悉使用这种字符替换,并且发现这些模式很难阅读和理解。我似乎无法在不破坏此 preg_replace 的部分或全部预期功能的情况下将它们加在一起。任何解释 and/or 示例将不胜感激。
您可以使用以下方式组合它们:
preg_replace( '/(?<!\d)([.,!?])(?![.,!?\d])|\s{2,}/', ' ', $filecontent);
直截了当的问题;如何将以下两个 preg_replace 模式合并为一个?
preg_replace( '/(?<!\d)[.,!?](?![.,!?\d])/', '[=11=] ', $filecontent);
preg_replace('/\s\s+/', ' ', $filecontent);
第一个来自this answer,而第二个简单地删除了过多的空格。
我尝试对链进行一些操作(请参阅下面注释掉的行),但这没有用——而且我认为这也不是最好的解决方案。
$fp2 = fopen($filepath, 'r+');
$filecontent = file_get_contents($filepath);
$correctedpunctation = preg_replace( '/(?<!\d)[.,!?](?![.,!?\d])/', '[=12=] ', $filecontent);
/* $correctedspacing = preg_replace('/\s\s+/', ' ', $correctedpunctation); */
/* fwrite($fp2, $correctedpunctation); */
fwrite($fp2, $correctedpunctation);
fclose($fp2);
我一直在努力阅读 regular expressions,但我不熟悉使用这种字符替换,并且发现这些模式很难阅读和理解。我似乎无法在不破坏此 preg_replace 的部分或全部预期功能的情况下将它们加在一起。任何解释 and/or 示例将不胜感激。
您可以使用以下方式组合它们:
preg_replace( '/(?<!\d)([.,!?])(?![.,!?\d])|\s{2,}/', ' ', $filecontent);