用php正则表达式替换方括号之间的子字符串

Liv*_*rce 3 php regex

这是我正在使用的子字符串

[sitetree_link%20id=2]
Run Code Online (Sandbox Code Playgroud)

我需要用空格替换[]之间出现的所有%20.但显然如果[]括号外有%20s,请不要管它们......

我现在正在学习正则表达式,但这个看起来很难.有人为此获得了超级聪明的正则表达式吗?

谢谢 :)

Nar*_*ala 5

你可以试试这个

$result = preg_replace('/(\[[^]]*?)(%20)([^]]*?\])/m', '$1 $3', $subject);
Run Code Online (Sandbox Code Playgroud)

说明

(          # 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
)
Run Code Online (Sandbox Code Playgroud)