Home > Blockchain >  getting img element by class name is returning too many results
getting img element by class name is returning too many results

Time:04-02

I'm using this code for a reg ex in order to get every img element that has the class 'wp-post-image' but it's getting images that don't have that tag just because they're close by:

$results = 'img src="https://api.follow.it" border=0 width="1" height="1"> <img width="150" height="150" src="https://www.sitefeed.com/testImage.jpg" <p>This is a test for RSS feeds</p>';
$pattern = '/<img. ?/';
preg_match($pattern, $results, $classMatches);
dump($classMatches);

with that HTML snippet, I'm getting both image elements in my dump.

How can I match ONLY the image with the matching class name?

CodePudding user response:

You can use following function:

function get_string_between(string $str, string $tagName, string $findClass = '')
{
   $tags = explode('<', $str);
              
   $classMatches = '';
              
   foreach ($tags as $tag) {
     if (strpos($tag, $tagName) !== false && strpos($tag, $findClass) !== false ) {
        $tag = str_replace('>', '', $tag);
        $classMatches .= '<' . $tag . '>';
     }
   }
    
   return $classMatches;

}

$classMatches = get_string_between($results, 'img', 'wp-post-image');
  • Related