【问题标题】:Delete words in sentence but not between double quotes删除句子中的单词,但不删除双引号之间的单词
【发布时间】:2018-09-24 16:24:50
【问题描述】:

我希望用替换而不是在双引号之间格式化一个句子。

例子,这句话:

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

应该是

“海”或“海”和“海”世界。

我认为我们可以使用 preg_replace 或 preg_match。 我找到了将文本放在双引号周围的正则表达式:

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

【问题讨论】:

标签: php regex preg-replace preg-match


【解决方案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

【讨论】:

  • 好像没问题,但是我们必须搜索单词而不是单词的一部分,所以我们必须在正则中的搜索周围添加一个空格,对吗?因为现在,如果你添加 $remplacement 'd',单词 'world' 的 d 将被删除
  • 您需要提供d 的示例,我无法复制3v4l.org/1a7lCfanéfanée 的问题可以通过添加 u 修饰符来解决。 3v4l.org/GikTB 单词边界应该使它不匹配部分匹配。
  • 好吧,我说的是“renaît”这个词的“t”,而不是世界的“d”。对不起。最后一个问题是我在 php 7.2
猜你喜欢
  • 2021-10-28
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
相关资源
最近更新 更多