【问题标题】:How to ignore specific words with preg_replace如何使用 preg_replace 忽略特定单词
【发布时间】:2018-06-29 13:06:31
【问题描述】:

考虑以下几点:

$string = "Hello, there! Welcome to <>?@#$!& our site<!END!>";

我正在尝试删除除字母、数字、空格和“特殊标签”&lt;!END!&gt;之外的所有内容@

使用 preg_replace,我可以这样写:

$string = preg_replace("/[^A-Za-z0-9 ]/", "", $string);

删除除字母(大写和小写)、数字和空格之外的所有内容。现在,如果我还想忽略&lt;!END!&gt; 标签,理论上我可以这样写:

$string = preg_replace("/[^A-Za-z0-9 <!END!>]/", "", $string);

但是,这不会特别忽略标签&lt;!END!&gt;,而是它包含的任何字符。所以它将保留每个 和 !在 $string 中。

结果:

"Hello there! Welcome to <>! our site<!END!>"

但我想得到:

"Hello there Welcome to  our site<!END!>"

根据我的研究,应该可以通过使用 \b 标签在 preg_replace 中包含要忽略的特定单词,但是 "/[^A-Za-z0-9 \b&lt;!END!&gt;\b]/" 给了我与上述相同的结果。

我做错了吗?

现场演示:http://sandbox.onlinephpfunctions.com/code/219dc36ab8aa7dfa16e8e623f5f4ba7f4b4b930d

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以使用(*SKIP)(*F) 解决方案:

    &lt;!END!&gt;(*SKIP)(FAIL)|[^A-Za-z0-9 ]

    那会匹配:

    • &lt;!END!&gt;(*SKIP)(FAIL) 匹配 &lt;!END!&gt; 然后跳过该匹配
    • |
    • [^A-Za-z0-9 ]不使用字符类中指定的匹配

    例如:

    $string = "Hello, there! Welcome to <>?@#$!& our site<!END!>";
    $string = preg_replace("/<!END!>(*SKIP)(FAIL)|[^A-Za-z0-9 ]/", "", $string);
    echo $string;
    

    这将导致:

    您好欢迎来到我们的网站

    Demo

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 2022-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2017-09-25
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      相关资源
      最近更新 更多