Alain
Alain

Reputation: 36984

Regular expression to match | but not ||

My goal is to split a string such as, a|b||c|d in a, b||c and d.

I tried using several methods, but end up splititng my string in any way:

Lookbehind:

var_dump(preg_split("/\\|(?<!\\|\\|)/", 'a|b||c|d'));

array (size=4)
  0 => string 'a' (length=1)
  1 => string 'b' (length=1)
  2 => string '|c' (length=2)
  3 => string 'd' (length=1)

Lookahead:

var_dump(preg_split("/(?!\\|\\|)\\|/", 'a|b||c|d'));

array (size=4)
  0 => string 'a' (length=1)
  1 => string 'b|' (length=2)
  2 => string 'c' (length=1)
  3 => string 'd' (length=1)

How can I just ignore doublepipes?

Upvotes: 1

Views: 39

Answers (2)

anubhava
anubhava

Reputation: 785621

You can use this regex for splitting:

(?<!\|)\|(?!\|)

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174796

Just split your input according to the below regex which uses negative lookarounds.

(?<!\|)\|(?!\|)

DEMO

| is a special meta character in regex which acts like a logical OR or alternation operator. To match a literal | symbol, you need to escape the | in your regex like \|

Upvotes: 4

Related Questions