Traverse string with PHP

Asked

Viewed 1,750 times

2

I need to traverse a string and within this string will come tags from imagens I need to select the first one. I’m using the strstr() but it’s not working.

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

How should I do to have the right goal ?

The reason for using this question is because I am saving a post where I give option to save with image along, but I need to preview this post where you make a thumbnail with the image. So I need to go through 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.

3 answers

5


You can use regular expressions!

To only handle the first image, you can make use of the function preg_match:

$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];

See on the Ideone.


If you want to handle all images, you can use the function 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;
}

See on the Ideone.

To limit yourself to the first, just skip the cycle to the first:

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

See on the Ideone.

  • what makes this PHP_EOL.$value ?

  • 1

    PHP_EOL is to open new line correctly on the platform in use (End Of Line), in combination with the echo allows to see the output in multiple lines... without it we would have imagem1.jpgimagem2.jpg ;)

  • Ual kkkkk thanks for the full answer !

1

Good afternoon.

As I understand it, do you intend to get the first picture right? I was just wondering if you wanted the image source or the full 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 misplaced image 1 to show how the code works.

To get the image CRS do $matchesSRC[1] and to get the full tag $matchesSRC[0].

I hope this helps you.

Cumps, James.

-3

public static function removerCaracteresEspeciaiss($str){
    $str_saida = "";
    for($i=0; $i<strlen($str); $i++){
        $num_asc = ord($str[$i]);
        if( ($num_asc>=65 && $num_asc<=90) || ($num_asc>=97 && $num_asc<=122) || ($num_asc>=48 && $num_asc<=57)){
            $str_saida .= $str[$i];
        }
    }
    return $str_saida;
}
  • 1

    How this solves the problem of fetching an image tag in a string???

Browser other questions tagged

You are not signed in. Login or sign up in order to post.