Home > OS >  Regex with OR operator not catching "double" matches
Regex with OR operator not catching "double" matches

Time:09-27

Using PHP's preg_match_all I have the following problem.

Example string:

last_name, first_name
bjorge, philip
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie

Regex:

/\bcredit\b|\bcredit note\b|\bfreddie\b/

Current Result:

array(1
  0 =>  array(2
    0   =>  credit
    1   =>  freddie
  )
)

Expected result:

array(1
  0 =>  array(3
    0   =>  credit
    1   =>  credit note
    2   =>  freddie
  )
)

https://www.phpliveregex.com/p/GeW#tab-preg-match-all

Probably a very common problem, but I was not able to find a solution.

CodePudding user response:

You can not revisit the same position twice to match the same string.

What you can do is put them in a lookahead with a capture group and make the credit part optional

$re = '/\b(?=((?:credit )?note|freddie)\b)/';
$str = 'last_name, first_name
bjorge, philip
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie';

preg_match_all($re, $str, $matches);
var_dump($matches[1]);

Output

array(3) {
  [0]=>
  string(11) "credit note"
  [1]=>
  string(4) "note"
  [2]=>
  string(7) "freddie"
}

CodePudding user response:

last_name, first_name
bjorge, philip
credit <-----  ;)
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie

change the input.

regex will match once, so based on your result you need to take into account that "credit note" contains "credit". maybe use preg_quote() if you are working in php.

  • Related