Cristal
Cristal

Reputation: 502

preg_replace img tag in sequence in PHP

I have a content, which is like

Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test

I would like to change it to be

Test test test <id>1</id> test test <id>2</id> test test

I have tried:

preg_match_all('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', $content, $result, PREG_SET_ORDER);
foreach($result as $val) {                
          $content = preg_replace('/<img(.*?)alt=\"(.*?)\"(.*?)>/si', '<id>'.$val[2].'</id>', $content);

But it gives me:

Test test test <id>2</id> test test <id>2</id> test test

Upvotes: 1

Views: 731

Answers (3)

troycurtisjr
troycurtisjr

Reputation: 56

It doesn't seem like preg_match* is the right function to use here, evidenced by the need to loop. It can be accomplished with just a preg_replace():

preg_replace("/<.*? alt=[\"']([0-9]+)[\"'] *>/", '<id>${1}</id>', $teststr);

This will operate on each matched expression independently, and do them all in one shot. If you decide you do need the src value, you can adjust the expression as necessary.

Upvotes: 1

Duc Filan
Duc Filan

Reputation: 7157

Your replacement inside the foreach contains problem. This is the fixed version.

<?php

$str = <<<term
Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test'
term;

preg_match_all('/<img.*?alt=[\'"](\d+)[\'"]>/', $str, $matches, PREG_SET_ORDER, 0);

foreach($matches as $val) {                
    $str = preg_replace('/<img.*?alt=[\'"](' . $val[1] . ')[\'"]>/', '<id>'.$val[1].'</id>', $str);
}

var_dump($str);

Check it out here: http://sandbox.onlinephpfunctions.com/code/ad70f171ec5387451a29166865474de0f223f7c1

Upvotes: 1

Kenneth
Kenneth

Reputation: 2993

Try this one.

    $data = `Test test test <img src="abc.png" alt='1'> test test <img src="123.png" alt='2'> test test`;

    $replace = ["<img src='abc.png' alt='1'>","<img src='123.png' alt='2'>"];
    $value = ["<id>1</id>","<id>2</id>"];

    $dataNeeded = str_replace($replace, $value, $emailContent);

echo $dataNeeded;

Upvotes: 0

Related Questions