-2

How to get number of image file name and image file name from php var ?

I have php var string like this

<p>aas sss ddd fff g gh ggg hhhh</p><p style="text-align: center; "><img src="threads_image/2rU4Va7c05b3f200c8cb893126fc7622b63f477ORZWM38.png" style="width: 240px;"></p><p style="text-align: left;"><img src="threads_image/2rU4V9cbdefa8e38d5457c8b1fc7ccb77c9dc30YQJUI9N.gif" style="width: 300px;"></p><p style="text-align: left;"><br></p><p style="text-align: left;"><img src="threads_image/2rU4V89e0e28ad1aab7c870d0df6380087ed378IGAN8BX.jpg" style="width: 794px;"><br></p>

So i want to get number of image file and image file name. how can i do that ?

I don't seen php function that can do that ?

  • what do you mean by "number of image file" ? – Frankich Nov 15 '16 at 16:43
  • it's mean number of image file name . in this case is `3` first is `2rU4Va7c05b3f200c8cb893126fc7622b63f477ORZWM38.png` second is `2rU4V9cbdefa8e38d5457c8b1fc7ccb77c9dc30YQJUI9N.gif` and third is `2rU4V89e0e28ad1aab7c870d0df6380087ed378IGAN8BX.jpg` – roboert fer Nov 15 '16 at 16:47
  • the better way is to watch about regex to catch your src – Frankich Nov 15 '16 at 17:01

2 Answers2

0

(not by me).

If you don't wish to use regex (or any non-standard PHP components), a reasonable solution using the built-in DOMDocument class would be as follows:

<?php
    $doc = new DOMDocument();
    $doc->loadHTML('<img src="http://example.com/img/image.jpg" ... />');
    $imageTags = $doc->getElementsByTagName('img');

    foreach($imageTags as $tag) {
        echo $tag->getAttribute('src');
    }
?>

the link of the awnser : Regex & PHP - isolate src attribute from img tag

Community
  • 1
  • 1
Frankich
  • 842
  • 9
  • 19
0

You can use regular expressions to find the image names. This regular expression should be fine: src=\"threads_image\/([^"]+). You can use it like so:

preg_match_all('/<img src=\"threads_image\/([^"]+)/', $html , $matches);

$matches[1] is now a list of the image names.

C:\Users\Thomas\Projects\stackoverflow\40615130\index.php:4:
array (size=2)
  0 => 
    array (size=3)
      0 => string '<img src="threads_image/2rU4Va7c05b3f200c8cb893126fc7622b63f477ORZWM38.png'     (length=74)
      1 => string '<img src="threads_image/2rU4V9cbdefa8e38d5457c8b1fc7ccb77c9dc30YQJUI9N.gif' (length=74)
      2 => string '<img src="threads_image/2rU4V89e0e28ad1aab7c870d0df6380087ed378IGAN8BX.jpg' (length=74)
  1 => 
    array (size=3)
      0 => string '2rU4Va7c05b3f200c8cb893126fc7622b63f477ORZWM38.png' (length=50)
      1 => string '2rU4V9cbdefa8e38d5457c8b1fc7ccb77c9dc30YQJUI9N.gif' (length=50)
      2 => string '2rU4V89e0e28ad1aab7c870d0df6380087ed378IGAN8BX.jpg' (length=50)

Please note that this only works if all the images share the directory threads_image.

Thomas
  • 537
  • 1
  • 4
  • 14