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

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

报告相同问题?

悬赏问题

  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52