Home > Software engineering >  Changing image links in text [PHP]
Changing image links in text [PHP]

Time:03-21

I want to replace the image links in the text with the following, but it doesn't. I'm sure everything is correct but I don't know what the problem is. Can you help me with this issue?

{#img='image_name.jpg', alt=''}

PHP code:

$text = "Hello <img src='https://example.com/image1.jpg'> , <img src='example.com/image2.jpg'> and now you :)";
    $re = '/<img.*?src=[\'"]([^"\'])[\'"]>/'; 
    preg_match_all($re, $text, $matches, PREG_SET_ORDER, 0);
    foreach ($matches as $val) {
        $str = preg_replace('/<img.*?src=[\'"](' . $val[1] . ')[\'"]>/', "{#img='" . $val[1] . "', alt=''}", $text);
    }
    var_dump($text);

Result:

Hello <img src='https://example.com/image1.jpg'> , <img src='https://example.com/image2.jpg'> and now you :)

CodePudding user response:

The reason there is no match is because in the pattern <img.*?src=[\'"]([^"\'])[\'"]> you have to repeat the character class ([^"\']*) because now you are matching exactly 1 occurrence.

Then in the foreach loop the replaced string is in variable $str because $text is not touched at all, it is only passed to preg_match_all.

But you don't need to match first, and then do a loop calling preg_replace separately.

You might use for example only preg_replace, and use the capture group 2 value that contains the url for the replacement.

$text = "Hello <img src='https://example.com/image1.jpg'> , <img src='example.com/image2.jpg'> and now you :)";
$str = preg_replace('/<img[^>]*src=([\'"])(.*?)\1>/', "{#img='$2', alt=''}", $text);

echo $str;

Output

Hello {#img='https://example.com/image1.jpg', alt=''} , {#img='example.com/image2.jpg', alt=''} and now you :)

See a regex demo for the matches on regex101 and a PHP demo on 3v4l.org.

  • Related