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

I suppose regex can do the trick, but I couldn't come up with one that works. I have some pretty long lines in PHP that I need to clear. In some cases, instead of   a space character appears, and in other cases,     (etc.). I would like to replace all single event   by space, but leave the rest in place so that you can intend to maintain.

Any thoughts? I guess you can use regex here, but I struggled to do this for a while!

+4
source share
2 answers

You must use a negative lookbehind and a negative lookahead to make sure you don't have another   .

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

More information about the search here .

+11
source

Use an explicit regular expression that matches (not-&nbsp;)&nbsp;(not-&nbsp;) , and add the replacement as $1 $2 (matching 1 to space 2). You may need to explicitly specify not-&nbsp; like ([^;]|[^p];|[^s]p;|[^b]sp;|[^n]bsp;|[^&]nbsp;) .

Change Although [negative] images can be useful (and, of course, less general code), you can measure the speed of each approach. I found that some mechanisms in regular expressions can be painfully slow compared to others, although I cannot speak directly with the speed of search queries. If speed becomes a problem, you can skip regular expressions and use a combination of strpos and substring operations and tests, which are often much faster than regular expressions, even if they are more cumbersome to create. I suggest this only because you have a very explicit string that you are looking for; with less defined lines, regex is definitely a way to go.

For this instance (in pseudo-code), finding the string strpos will be as simple as strpos($mystring, "&nbsp;") , and as soon as you find a match, call strpos($mystring, "&nbsp;&nbsp;") . If two calls to index return the same value, you can skip this replacement and do a row search after the indexed point (run your single &nbsp; search after indexDoubleFound + 12 , but run a double search &nbsp; after indexDoubleFound + 6 so you don't miss nobody, and you do not accidentally replace).

+1
source

Source: https://habr.com/ru/post/1492361/


All Articles