Go through string with PHP

2

I need to go through a string and within this string will come tags of imagens I need to select the first one. I am using strstr() but it is not working.

$img = strstr($texto, '%img');
echo $img;

How do I get the goal right?

  

The reason for using this question is because I'm saving a post where I give option to save with image together, but I need to preview this post where it does a thumbnail with the image. So I need to go through all of this string so that I can identify which image relates to that post so I can go to the folder and identify to mount the thumbnail.

    
asked by anonymous 08.07.2015 / 20:06

2 answers

5

You can use regular expressions!

To deal only with the first image, you can use the preg_match function:

$html = 'Muita cena aqui pelo meio e com tags<br><img alt="imagem 1" src="imagem1.jpg"/><br/><img alt="imagem 2" src="imagem2.jpg"/><br/>';

preg_match('@<img.+src="(.*)".*>@Uims', $html, $matches);

echo $matches[1];

View on Ideone .

If you want to deal with all images, you can use preg_match_all :

$html = 'Muita cena aqui pelo meio e com tags<br><img alt="imagem 1" src="imagem1.jpg"/><br/><img alt="imagem 2" src="imagem2.jpg"/><br/>';

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

foreach ($matches[1] as $key=>$value) {
    echo PHP_EOL . $value;
}

View on Ideone .

To limit yourself to the first, simply exit the cycle at first:

foreach ($matches[1] as $key=>$value) {
    echo PHP_EOL . $value;
    break;
}

View on Ideone .

    
08.07.2015 / 20:23
1

Good afternoon.

As I understand it, do you want to get the first correct image? I was in doubt if you wanted the image source or the complete tag ... so I did the following.

<?php

$str = '<im src="urlexemplo/imagem1.png"/><img src="urlexemplo/imagem2.png"/>';

preg_match('/< *img[^>]*src *= *["\']?([^"\']*)[^>]+>/i', $str, $matchesSRC);

var_dump($matchesSRC);

Or you can see how it works, here .

I put the image 1 in error to see how the code works.

To get the SRC of the image you do $matchesSRC[1] and to get the complete tag you make $matchesSRC[0] .

I hope this helps you.

Cumps, James.

    
08.07.2015 / 20:31