2

I already asked the question how to get the string fields from a pipe-separated string with pipe-escaping, and got an answer that worked well on http://www.regex101.com: a regex to get the single words of a pipe-separated string, supporting pipe-escaping.

Unfortunately this does not seem to work in PHP's preg_match_all() function:

$input   = 'word1| word 2 |word\|3';
$pattern = '/(?P<w>(?:[^\\|]+|\\\|?)+)/';
$matches = array();

preg_match_all($pattern,$input,$matches);

// Expected $matches: $matches['w'] => array('word1', ' word 2 ', 'word\|3')

What am I missing? The example is working fine here:

https://regex101.com/r/zM7yV5/4

Community
  • 1
  • 1
Alex Schenkel
  • 636
  • 1
  • 7
  • 12
  • it's because of the forward slash as delimiter. Just use a different php delimiter with the same regex. That is, `$pattern = '~(?P(?:[^\\|]+|\\\|?)+)~';` – Avinash Raj Jan 29 '15 at 12:53
  • No, it's not: 1) I'm not matching against a '/' character, and 2) using another delimiter does not work, either. See vks' answer below, which is correct. – Alex Schenkel Jan 29 '15 at 17:38

1 Answers1

1
$re = "/(?P<w>(?:[^\\\\|]+|\\\\\\|?)+)/";
$str = "word1| word 2 |word\|3";

preg_match_all($re, $str, $matches);
vks
  • 63,206
  • 9
  • 78
  • 110
  • Thanks, that helped. So many backslashes :-( Why do I have to escape the backslash here, but not e.g. in something like /\d+/? I think I don't need to escape the backslash itself for the PHP string, as I am using single quotes...? – Alex Schenkel Jan 29 '15 at 13:34
  • No, here the delimiter was not the problem, as I dont want to match '/' itself. Even with another delimiter I need that amount of backslashes. – Alex Schenkel Jan 29 '15 at 14:11
  • @AlexSchenkel try with `~`.You might not need these many `\\`. – vks Jan 29 '15 at 14:13