duanlu7680 2018-06-29 13:06
浏览 74
已采纳

如何使用preg_replace忽略特定单词

Consider the following:

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

I'm trying to remove everything except for letters, numbers, spaces, and the "special tag" <!END!>

Using preg_replace, I can write this:

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

To remove everything except letters (both capital and lowercase), numbers, and spaces. Now if I wanted to also ignore the <!END!> tag, in theory I could write this:

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

However this will not specifically ignore the tag <!END!>, but rather any of the characters it contains. So it'll be preserving every <, >, and ! in $string.

The result:

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

But I'm trying to get:

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

Based on my research, it should be possible to include a specific word to ignore in preg_replace by using the \b tags, however "/[^A-Za-z0-9 \b<!END!>\b]/" gave me the same result as above.

Am I doing something wrong?

Live demo: http://sandbox.onlinephpfunctions.com/code/219dc36ab8aa7dfa16e8e623f5f4ba7f4b4b930d

  • 写回答

1条回答 默认 最新

  • doubaomao9304 2018-06-29 13:25
    关注

    You could use a (*SKIP)(*F) solution:

    <!END!>(*SKIP)(FAIL)|[^A-Za-z0-9 ]

    That would match:

    • <!END!>(*SKIP)(FAIL) match <!END!> and then skip that match
    • | or
    • [^A-Za-z0-9 ] Match not using what is specified in the character class

    For example:

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

    That will result in:

    Hello there Welcome to our site<!END!>

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复