I want to perform a regex using grouping. I am only interested in the grouping, its all I want returned. Is this possible?
$haystack = '<a href="/foo.php">Go To Foo</a>';
$needle = '/href="(.*)">/';
preg_match($needle,$haystack,$matches);
print_r($matches);
//Outputs
//Array ( [0] => href="/foo.php"> [1] => /foo.php )
//I want:
//Array ( [0] => /foo.php )
Actually this is possible with lookarounds. Instead of:
You want
Now this will match (and therefore capture into group 0) any
.*that is preceded byhref="and followed by">. Note that I highly suspect that you really need.*?instead, i.e. reluctant instead of greedy.In any case, it looks like PHP’s
pregis PCRE, so it should support lookarounds.regular-expressions.info links
pregfunctions implement the PCRE flavor.(?=regex)(positive lookahead): YES(?<=text)(positive lookbehind): fixed + alternationDemonstration
Running this on ideone.com produces:
Related questions
These are mostly Java, but the regex part covers using lookarounds/assertions: