0

Let's say that i have more a href elements with different class names on a page "tst.php" like this:

<a class='1' href='etc.html'>Link</a>
<a class='2' href='etc.html'>Link</a>
<a class='3' href='etc.html'>Link</a>
<a class='4' href='etc.html'>Link</a>
<a class='5' href='etc.html'>Link</a>
<a class='1 2' href='etc.html'>Link</a>
<a class='1 4' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='2 3' href='etc.html'>Link</a>
<a class='2 1' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='5 2 6' href='etc.html'>Link</a>
<a class='5 2 6 7' href='etc.html'>Link</a>
<a class='5 2 5 7 8 9 4 6 2 6' href='etc.html'>Link</a>

i want to make a php code that will echo in another page "echo.php" onli the a href's elements that have class name 2 in their values.

Something Like this

<?php
$stream = readfile("tst.php");
$regex = "class= '2'"
preg_match_all($regex,$Text,$Match);
echo $Match all;
?>

And the echo should be only the Href's that are class named with "2":

<a class='2' href='etc.html'>Link</a>
<a class='1 2' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='2 3' href='etc.html'>Link</a>
<a class='5 2' href='etc.html'>Link</a>
<a class='5 2 6' href='etc.html'>Link</a>
<a class='5 2 6 7' href='etc.html'>Link</a>
<a class='5 2 5 7 8 9 4 6 2 6' href='etc.html'>Link</a>

Thanks in Advance!

John Conde
  • 217,595
  • 99
  • 455
  • 496

1 Answers1

3

You shouldn't use regular expressions for parsing HTML. You should use tools designed for this like DomDocument. Here's a basic example:

<?php
$dom = new DOMDocument();
@$dom->loadHTML($string_with_html);
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor) {
    $class = $anchor->getAttribute('class');
    if (strstr($class, '2')) {
        echo $dom->saveHTML($anchor) . "<br>\n";
    }
}

See it in action

You could also use xpath:

$dom = new DOMDocument();
@$dom->loadHTML($string_with_html);
$xpath = new DOMXpath($dom);
$anchors = $xpath->query('//a[contains(@class,"2")]');
foreach ($anchors as $anchor) {
     echo $dom->saveHTML($anchor) . "<br>\n";
}
Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496