简体   繁体   中英

Use PHP to find text within an HTML Page

I would like to write some PHP code to parse some HTML to return the href and title of all of the images in the "image_url" a class. I am currently using substr to find the location of the strings, however the webpage sometimes changes content and I can't always rely on substr. Is there a DOM way or some other regular expression way I can find these elements within my HTML?

<a class="image_url" href="/123.jpg" target="_blank"><img src="/123.jpg" border="0" title="Some dynamic length image title that is making this difficult for me"></a>

You can use the 3 things as far as I know

  1. php simple xml parsing
  2. php domDoucment.
  3. Simplehtmldom parser

You can try below sample code.

$html='<a class="image_url" href="/123.jpg" target="_blank"><img src="/123.jpg" border="0" title="Some dynamic length image title that is making this difficult for me"></a>';   
 $dom = new DOMDocument();
    $dom->loadHTML($html);

    $elements = $dom->getElementsByTagName('a');
    foreach ($elements as $child) {
        echo $child->nodeValue;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM