正则表达式匹配PHP

I’m trying to perform a regex match in PHP and I wonder how to do it correctly.

I looked into preg_match and things but it looks very confusing for a newbie like me.

I know that in AHK (AutoHotKey) I can use this command:

regexmatch(var, "<td style=""""><a.*?>(.*?)</", out)

And var is:

<td style=""><a href="/player/33598934">tofind</a></td>

and then variable out1 would be:

tofind

But how can I achieve this in PHP?

The documention states clearly how to use preg_match(), it briefly explains these parameters.

preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

Only difference is you would need to use different delimiters, and reduce the double quotes in your regex.

preg_match('~<td style=""><a.*?>(.*?)</~', $str, $match);
echo $match[1]; //=> "tofind"

Note: Here we use $match[1] to access what was matched in capturing group #1


It is alot easier and preferred to use a Parser instead when it comes to parsing HTML.

$dom = new DOMDocument;
$dom->loadHTML($html); // Load your HTML data

$xpath = new DOMXPath($dom);
$node  = $xpath->query("//td//a");

echo $node->item(0)->nodeValue;

Working Demo

use this:

preg_match('_<td style=""><a href="/player/33598934">(\w*)</a></td>_','<td style=""><a href="/player/33598934">tofind</a></td>',$out);

echo $out[1];