Tutorial :How do I match adjacent pairs of delimiters in php based Perl compatible regex?


I have a string which could contain multiple delimiters right next to each other, for example |||, although it could be any number of adjacent delimiters. I need to replace any place "in between" the adjacent pair with a specific character. These delimiters will only need to match if there is no character between the delimiter, not even spaces.

So Replace:

ABC|||Blah     with     ABC|*|*|Blah  

However, when I try it, it will not "fill in" the gap between all of them. In the same example above it only results in ABC|*||Blah
Four delimiters result in ABC|*||*|Blah

How do I write a regex pattern that will do what I need? I am using php's preg_replace.


Using both look-ahead and look-behind:


replace globally with



The answer that worked for me turned out to be a positive lookahead.


This matched all places where the delimiters were strictly adjacent. That the second delimiter, in the forward lookahead, was not considered as part of the match was the key to allow me to match them in the example mentioned.


Why not working with str_replace:

$str = str_repalce('||', '|*|', str_replace('||', '|*|', $str));  

Edit   As I think I know understand what you are looking for, there are three cases the gaps can occur:

  1. at the start: |foo|bar â†' *|foo|bar
  2. in the middle: foo||bar â†' foo|*|bar
  3. at the end: foo|bar| â†' foo|bar|*

The latter two can be handled at once, but the first has to be handled separatly:

$str = preg_replace('/^\|/', '*|', preg_replace('/\|(?=\||$)/', '|*', $str))  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »