mikatakana
mikatakana

Reputation: 523

PHP: preg_match `eats` my string

Parsing code

$str = 'My name is Michael. I am a sportsman!';
preg_match('|My name is (.*?)\. I am a (.*?)|', $str, $m);
print_r($m);

returns me string:

Array ( [0] => My name is Michael. I am a [1] => Michael [2] => )

Where is sportsman?

Upvotes: 2

Views: 86

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173572

That's because the expression is not anchored, or rather, the second (.*?) doesn't have a look-ahead set and therefore matches nothing); you should add the end-of-string anchor like this:

preg_match('|My name is (.*?)\. I am a (.*?)$|', $str, $m);
                                            ^

You could also make the second expression greedy:

preg_match('|My name is (.*?)\. I am a (.*)|', $str, $m);
                                          ^

Upvotes: 5

Related Questions