How to replace words with preg_replace without duplicates?

后端 未结 1 1743
小鲜肉
小鲜肉 2021-01-24 12:00

I want to create a PHP function which will replace certain words out of a text with internal links. That works so far, but if I have two matches, I end up with invalid HTML code

相关标签:
1条回答
  • 2021-01-24 12:32

    Instead of using a loop, construct a single regular expression and modify your entire document in a single pass. That is, instead of these regular expressions:

    ~\b(foo)\b~i
    ~\b(bar)\b~i
    ~\b(baz)\b~i
    

    Use just this one:

    ~\b(foo|bar|baz)\b~i
    

    You might want to look at using implode to contruct the regular expression.

    You also need to be careful of characters that have a special meaning inside a regular expression. You may find preg_quote useful for this.

    0 讨论(0)
提交回复
热议问题