用php regex替换方括号之间的子字符串


Replace a substring that is between square brackets with php regex

这是我正在处理的子字符串

[sitetree_link%20id=2]

我需要用空格替换在[]之间出现的所有%20。但很明显,如果[]括号外有%20,不要管它们…

我现在正在学习正则表达式,但这个似乎很难。谁有超级聪明的正则表达式?

谢谢:)

你可以试试这个

$result = preg_replace('/('[[^]]*?)(%20)([^]]*?'])/m', '$1 $3', $subject);

(          # Match the regular expression below and capture its match into backreference number 1
   '[         # Match the character “[” literally
   [^]]       # Match any character that is NOT a “]”
      *?         # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
(          # Match the regular expression below and capture its match into backreference number 2
   %20        # Match the characters “%20” literally
)
(          # Match the regular expression below and capture its match into backreference number 3
   [^]]       # Match any character that is NOT a “]”
      *?         # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
   ']         # Match the character “]” literally
)