Home > Net >  PHP - How to modify matched pattern and replace
PHP - How to modify matched pattern and replace

Time:03-19

I have string which contain space in its html tags

$mystr = "< h3> hello mom ?< / h3>"

so i wrote regex expression for it to detect the spaces in it

$pattern = '/(?<=&lt;)\s\w |\s\/\s\w |\s\/(?=&gt;)/mi';

so next i want to modify the matches by removing space from it and replace it, so any idea how it can be done? so that i can fix my string like "&lt;h3&gt; hello mom ?&lt;/h3&gt;"

i know there is php function pre_replace but not sure how i can modify the matches

$result = preg_replace( $pattern, $replace , $mystr );

CodePudding user response:

You could keep it simple and do:

$output = str_replace(['&lt; / ', '&lt; ', '&gt; '],
                      ['&lt;/',   '&lt;',  '&gt;'], $input);

CodePudding user response:

For the specific tags like you showed, you can use

preg_replace_callback('/&lt;(?:\s*\/)?\s*\w \s*&gt;/ui', function($m) { 
    return preg_replace('/\s /u', '', $m[0]); 
}, $mystr)

The regex - note the u flag to deal with Unicode chars in the string - matches

  • &lt; - a literal string
  • (?:\s*\/)? - an optional sequence of zero or more whitespaces and a / char
  • \s* - zero or more whitespaces
  • \w - one or more word chars
  • \s* - zero or more whitespaces
  • &gt; - a literal string.

The preg_replace('/\s /u', '', $m[0]) line in the anonymous callback function removes all chunks of whitespaces (even those non-breaking spaces).

  • Related