Regex replace word when not enclosed in brackets

后端 未结 2 786
臣服心动
臣服心动 2020-12-22 08:20

I\'m trying to create a regular expression where it replaces words which are not enclosed by brackets.

Here is what I currently have:

$this->parse         


        
2条回答
  •  有刺的猬
    2020-12-22 09:07

    After another morning of playing with the regex I came up with a quite dirty solution which isn't flexible at all, but works for my use case.

    $this->parsed = preg_replace('/\b(?!\[(|((\w+)(\s|\.))|((\w+)(\s|\.)(\w+)(\s|\.))))('.preg_quote($word).')(?!(((\s|\.)(\w+))|((\s|\.)(\w+)(\s|\.)(\w+))|)\[)\b/s','[$10['.implode(",",array_unique($types)).']]',$this->parsed);
    

    What it basically does is check for brackets with no words, 1 word or 2 words in front or behind it in combination with the specified keyword.

    Still, it would be great to hear if anyone has a better solution.

提交回复
热议问题