Marcello Impastato Marcello Impastato -4 years ago 130
PHP Question

How clear internal delimiter between two external delimiter

what regular expression i can use for match two or more delimitator internal a two delimitator and clear it? Some example:

1) input: %word1 %word2%% then output: %word1 word2%
2) input: %word1 %word2% %word3%%% then output: %word1 word2 word3%
3) input: %%word1 word2% word3% then output: %word1 word2 word3%

and so on.
Or apply a replace ignoring a substring from two delimiter, for example having:

%word1 word2% text word2

replacing word2 with %word2% without apply it to %word1 word2% having so as output something as:

%word1 word2% text %word2%

and not:

%word1 %word2%% text %word2%

Thanks very much.

Answer Source

For the second part of the question:

$ cat a.php
   echo preg_replace('/(?<!%)(word2)(?!%)/', '%word2%', '%word2% %word1 word2% text word2');
$ php a.php
%word2% %word1 word2% text %word2%

The regex works like this:


Regular expression visualization

Debuggex Demo

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