Jgtb
Jgtb

Reputation: 13

Find and replace multiple attributes from img tag using PHP RegEx

//Example of image
$image = '<img src="../img/image.jpeg" title="Title" alt="Alt"/>';

I have all this $patterns where i can take the value one at a time

// get the src for that image
$pattern_src = '/src="([^"]*)"/';

// get the title for that image
$pattern_title = '/title="([^"]*)"/';

// get the alt for that image
$pattern_alt = '/alt="([^"]*)"/';

How can i use all this $patterns with preg_replace like this:

preg_replace($pattern_src+$pattern_title+$pattern_alt,$1$2$3,$image);

Values

$1 => src value
$2 => title value
$3 => alt value;

Why i need it

<figure>
    <figcaption>
    $2 //Title value
    </figcaption>
    <img src="../web/img/$1"> //New src 
    <figcaption>
    $3 //Alt value
    </figcaption>
</figure>

Upvotes: 1

Views: 581

Answers (1)

rjdown
rjdown

Reputation: 9227

Obligatory comment about not using regex to parse HTML, and to use DOMDocument or something instead, blah blah blah. Anyway...

Two options here.

First, if the attributes are always in the same order, you can simply separate your current rules with a .*:

'/.*src="([^"]*)".*title="([^"]*)".*alt="([^"]*)"/'

Second option, if they are not always in the same order, you can use positive lookaheads:

'/(?=.*src="([^"]*)")(?=.*title="([^"]*)")(?=.*alt="([^"]*)")/'

This will return src, title and alt as $1, $2 and $3 respectively, no matter what order they appear in the image tag. Demo here

Upvotes: 1

Related Questions