1
//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>
2
  • you want to just extract out src, title and alt and use it somewhere else..right? Commented Mar 9, 2016 at 0:33
  • Exactly, But I need to do at the same time Commented Mar 9, 2016 at 0:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response, I tried your example and the value of title and alt also src worked perfectly, but created many identical images ... You have idea why this happened? @rjdown
The second option @rjdown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.