I'm trying a regex match, but am getting unexpected results. What am I doing wrong?
$text = "one two three?four five six?";
preg_match("~(.+?)(?:\?)?~", $text, $match);
print_r($match);
Result:
Array ( [0] => o [1] => o )
Expected Result:
Array ( [0] => one two three? [1] => one two three )
You need to remove the ?
next to non-capturing group which makes that non-capturing group as optional. Since the ?
is optional, (.+?)
non-greedy pattern should match and capture only the first character.
preg_match("~(.+?)\?~", $text, $match);