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

用php正则表达式替换方括号之间的子字符串,php,regex,Php,Regex,这是我正在使用的子字符串 [sitetree_link%20id=2] 我需要将所有出现在[]之间的%20替换为空白。但很明显,如果[]大括号外有%20个,请不要管它们 我现在只是在学习正则表达式,但这个似乎很难。有人为此买了超级聪明的正则表达式吗 谢谢:)你可以试试这个 $result = preg_replace('/(\[[^]]*?)(%20)([^]]*?\])/m', '$1 $3', $subject); 解释 ( # Match the regular ex

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

[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
)

啊,差不多了!只需要用一个空的空间来代替,即“代替”“非常感谢:)太好了,也为解释干杯。祝你周末愉快!非常感谢您的解释,这非常有帮助!!