phphtmlregex

How can I replace single  's with a space but, not if there are multiple  s?


I assume a regular expression might do the trick but I haven't been able to come up with one that works. I have some fairly long strings in PHP that I need to clean up. In some cases,   appears in stead of a single space character and in other caes     (etc) appears. I'd like to replace all of the single   occurence with a space but leave the others in place so that the intending can be maintained.

Any thoughts? I presume a regular expression could be used here but I've been struggling with making one for for a while!


Solution

  • You must use a negative lookbehind and a negative lookahead to ensure that you don't have other   around.

    $str = preg_replace('~(?<!&nbsp;)&nbsp;(?!&nbsp;)~i', ' ', $str);
    

    More informations about lookarounds here.


    Other way: match systematically all &nbsp; repeated or not, and force the pattern to fail when there are more than one occurrence with backtracking control verbs ((*SKIP) and (*FAIL)).

    $str =  preg_replace('~&nbsp;(?:(?:&nbsp;)+(*SKIP)(*F))?~i', ' ', $str);