Замените подстроку, которая находится между квадратными скобками с помощью php regex

Вот подстрока, с которой я работаю

[sitetree_link%20id=2] 

Мне нужно заменить все вхождения% 20, которые падают между [] с пробелом. Но, очевидно, если есть% 20s вне [] скобок, оставьте их в покое …

Я просто изучаю regex сейчас, но этот кажется довольно жестким. Кто-нибудь получил супер-умное регулярное выражение для этого?

Благодаря 🙂

Solutions Collecting From Web of "Замените подстроку, которая находится между квадратными скобками с помощью php regex"

Вы можете попробовать это

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