删除句子中的单词,但不要删除双引号之间的单词

时间:2018-09-24 16:24:50

标签: php regex preg-replace preg-match

我希望使用替换形式而不是双引号之间的句子格式。

示例,这句话:

$remplacement = ['the', 'in']; // words who must be deleted
$sentence = "the sea" OR the sea AND "the sea" in the world.

应该

  

“海”或“海”与“海”世界。

我认为我们可以使用preg_replace或preg_match。 我找到了正则表达式,它使用双引号引起来的文本:

'/[^"]+(?=(?:[^"]*"[^"]*"[^"]*)*$)/'

1 个答案:

答案 0 :(得分:1)

您可以忽略带PCRE动词的引用单词。然后,您可以使用“或”将这些术语内插,然后将其替换。您应该使用单词边界,以免替换部分匹配。

$remplacement = ['the', 'in'];
$sentence = '"the sea" OR the sea AND "the sea" in the world.';
echo preg_replace('/([\'"]).*?\1(*SKIP)(*FAIL)|\b(' . implode ('|', $remplacement) . ')\b/', '', $sentence);

https://3v4l.org/ZELoV

您的示例不正确,对吧?最后,the world也应成为world

如果您担心双倍间距,可以使用:

preg_replace('/\h\h+/', ' ',

摆脱它。

https://3v4l.org/pqCH3

相关问题