-1

How to search src and srcset tag in string using php ?

Normally i use this code for search src tag in $source string

    preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)/i', $source, $output);
    $src_tag_length =  count($output[0]);

Then i want to search src and srcset tag in $source string using php.

How can i do that ?

    preg_match_all('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $source, $output);
    $src_srcset_tag_length =  count($output[0]);
mamiw
  • 123
  • 4
  • 9
  • 4
    [Don't use regexes for parsing HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – John Conde Feb 26 '18 at 15:19
  • I have upvoted this question not because it's great, but because I don't think it deserves to be downvoted. While the regexp based approach is clearly insufficient, we require from questioners to show us what they have tried already. It's a perfectly fine question to be answered with "use a context free parser" as demonstrated by MonkeyZeus – ooxi Feb 26 '18 at 16:56
  • @ooxi We also require that the OP has done research on their question first. Any research on the topic of "how to parse HTML with regex" would quickly reveal that one shouldn't, and should instead attempt another method. Had the OP posted this question showing an attempt to solve this problem using DOMDocument, it likely wouldn't have been downvoted. – Patrick Q Feb 26 '18 at 17:03

1 Answers1

2

I would not use regex for this as it is notoriously prone to user error.

You can and should use PHP's DOMDocument class:

<?php
$html = '<html><body><img src="somethign.jpg"><img srcset="another.jpg"></body></html>';

$dom = new DOMDocument();
$dom->loadHTML( $html );

echo '<pre>';
foreach( $dom->getElementsByTagName( 'img' ) as $node )
{
    // Take notice that some img's src and srcset is not set
    // but getAttribute() still returns an empty string
    var_dump( $node->getAttribute( 'src' ) );
    var_dump( $node->getAttribute( 'srcset' ) );
}
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • How to get image url for use sir ? and how to get image length sir ? thank you. – mamiw Feb 27 '18 at 01:59
  • @mamiw `$node->getAttribute( 'src' )` gives you the image URL. You can use [`strlen()`](http://php.net/manual/en/function.strlen.php) to get the length of the image string. Please accept my answer if it has solved everything in your original question. – MonkeyZeus Feb 27 '18 at 12:23