将两个preg_replace模式合并为一个

时间:2015-02-10 18:04:58

标签: php regex string formatting 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的某些或所有预期功能的情况下将它们添加到一起。任何解释和/或示例都将非常感激。

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法合并它们:

preg_replace( '/(?<!\d)([.,!?])(?![.,!?\d])|\s{2,}/', '$1 ', $filecontent);

RegEx Demo