# Regural expression strange behaviour

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
I have the following code (I need to extract everything between
slash):

\$buff="0,x,R / 1,y,R / - / 1,y,R";

preg_match_all("/\s*([0-9]\s*,\s*[a-z]\s*,\s*.\s*)\s*[\/]\s*|\s*(-)\s*[\/]/U",\$buff,\$izlaz);

var_dump(\$izlaz);

This outputs:

array(3) {
[0]=>
array(4) {
[0]=>
string(7) "0,x,R /"
[1]=>
string(8) " 1,y,R /"
[2]=>
string(4) " - /"
[3]=>
string(8) " 1,y,R"
}

[1]=>
array(4) {
[0]=>
string(5) "0,x,R"
[1]=>
string(5) "1,y,R"
[2]=>
string(0) ""
[3]=>
string(5) "1,y,R"
}

[2]=>
array(4) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(1) "-"
[3]=>
string(0) ""
}
}

Problem is in the 3rd row: why is it there? I would expect '-' sign in
2nd row...

## Re: Regural expression strange behaviour

Hm, this is partial solution...

preg_match_all("/(\s*[0-9]\s*,\s*[a-z]\s*,\s*[LR]\s*\s*|\s*[\-]\s*)[\/]\s*/U",\$buff,\$izlaz);

## Re: Regural expression strange behaviour

Josip wrote:

preg_match_all("/\s*([0-9]\s*,\s*[a-z]\s*,\s*.\s*)\s*[\/]\s*|\s*(-)\s*[\/]/U",\$buff,\$izlaz);

below doesn't come from that.

No it doesn't.  There are only three matches to the full

The last string here doesn't match because there must be a
slash at the end.  You should allow the last slash to be

`(\d\s*,\s*[a-z]\s*,\s*.|-)\s*/?`

[ ... ]

Your subject string is '0,x,R / 1,y,R / - / 1,y,R'.  The
hyphen is in the third segment, not the second.  Move the
hyphen to the second segment and watch what happens.

--
Jock