How to display the found matches of preg_match function in PHP?
I am using the following to check if links exist on file.php:
$fopen = fopen('file.php', 'r');
$fread = fread($fopen, filesize('file.php'));
$pattern = "/^<a href=/i";
if (preg_match($pattern, $fread)) {
echo 'Match Found';
} else {
echo 'Match Not Found';
}
if I echo preg_match($pattern, $fread)
I get a boolean value, not the found matches. I tried what was on the php.net manual and did th开发者_高级运维is:
preg_match($pattern, $fread, $matches);
then when I echoed $matches I got "Array" message. So I tried a foreach loop and when that didn't display anything I tried $matches[0] and that too outputted nothing.
So how does one go about displaying the matches found?
EDIT
Here is the only content of file.php:
<a href="">Hello</a>
<a href="http://google.com">Hello</a>
<a href="/index.html">Hello</a>
To get the links you're looking for to actually show up you need to have match groups within your regular expression: (note I also added the m
modifier to deal with multiple lines)
$pattern = "/^<a href=(.*?)>/im";
Then, if you just want to visualize the contents of that match result array for debugging you can use print_r
.
if (preg_match_all($pattern, $fread, $matches)) {
echo 'Match Found';
print_r($matches);
} else {
echo 'Match Not Found';
}
A better approach is to use DOMDocument to parse the HTML document
$dom = new DomDocument;
$dom->loadHTMLFile('file.php');
$nodes = $dom->getElementsByTagName('a');
foreach ($nodes as $node)
{
echo simplexml_import_dom($node)->asXML(), '<br/>';
}
精彩评论