views:

34

answers:

1

I've been looking at this code and it's supposed to match my $input string and in $matches[0] store 'testing'

$input = ':testing';
$r = preg_match('/^(?<=\:).+/',$input,$matches);

What's wrong with it?

+4  A: 

(?<=) is a positive look-behind, which means that the text matching the enclosed expression must occur before the position of the parenthetical in the pattern. In this case, it means it must occur after the start-of-string position (^), but before the first actual character (.+ matches all of the characters in the string here), and since the : is the first actual character, and there's no : before the : (obviously), it fails to match.

Instead, what you probably want to do is use a capture group, like so:

$input = ':testing';
$r = preg_match('/^:(.+)/',$input,$matches);

// $matches[0] has the entire text matched by the pattern, ":testing"
// $matches[1] will now contain "testing" from the first capture

Thus you use $matches[1] to get the text from within the capture group, which is what you want.

Amber
+1 - You've beat me two answers in a row now lol.
Andy E
+1 you could also remove `^` in the original regex.
Felix Kling
Removing the `^` in the original regex could change the meaning and what is matched, Felix, since it would now partial-match on things like `"abc:testing"`, whereas the original regex very clearly was looking at whole strings only.
Amber
Thank you very informative.
JavaRocky
If you really needed the result to be in `$matches[0]` *and* for the match to be anchored, you could put the anchor inside the lookbehind: `/(?<=^:).+/`
Alan Moore