dany dany -4 years ago 162
PHP Question

PHP Regex: Matching "Space" if only within delimiter

I need to match only "spaces" that appear within delimiter [ ] so i can change the space with $.

Here is the text:


[Edit the] Expression & [Text to see matches]. Roll [over matches or
the] expression for details. Undo mistakes with ctrl-z. [Save
Favorites and Share expressions with friends] or the Community.
Explore your results with Tools. [A full Reference and Help is
available in the Library or watch the video Tutorial].


Here is my regex pattern:

$pattern = preg_replace('/(?!\[[a-z]+)( )(?=[a-z]+\])/','$',$newString);


I use regexr.com to test my pattern. The output from that pattern look like this:

regexr

How do i matches only "spaces" that appear within delimiter [ ] Thank you.

Answer Source

You may use

(?:\G(?!\A)|\[)[^]\s]*\K\s+

See the regex demo

Details:

  • (?:\G(?!\A)|\[) - the end of the previous successful match (\G(?!\A)) or (|) the [ symbol
  • [^]\s]* - 0 or more chars other than ] and whitespace
  • \K - match reset operator omitting all text matched so far in the current iteration
  • \s+ - 1+ whitespaces

PHP demo:

$str = '[Edit the] Expression & [Text to see matches]. Roll [over matches or the] expression for details. Undo mistakes with ctrl-z. [Save Favorites and Share expressions with friends] or the Community. Explore your results with Tools. [A full Reference and Help is available in the Library or watch the video Tutorial].';
$result = preg_replace('~(?:\G(?!\A)|\[)[^]\s]*\K\s+~', '$', $str);
echo $result;

Another approach: match [...] substrings (with the \[[^][]+] pattern) and only replace whitespace inside the matches with preg_replace_callback:

$result = preg_replace_callback('~\[[^][]+]~', function ($m) {
    return preg_replace('~\s+~', '$', $m[0]);
}, $str);

See another PHP demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download