I have some text with images within it. I want to replace specific images within the text with something else.
i.e. the text contains an a youtube img url that I want to replace with the actual video link.
<img class="mceItem" src="http://img.youtube.com/vi/1MsVzAkmds0/default.jpg" alt="1MsVzAkmds0">
and replace it with the youtube Iframe code:
<iframe title="'.$id.'" class="youtube-player" type="text/html" width="576" height="400" src="http://www.youtube.com/embed/'.$id.'" frameborder="0"></iframe>
my function looks like this:
function replacelink($link) {
$find= ("/<img src=[^>]+\>/i");
$replace = youtube("\\2");
return preg_replace($find,$replace);
}
What do I need to change in the regex to do the above?
Your regex is looking for
<img src=, but there is aclassattribute betweenimgandsrc. Using$find= '/<img.*src=[^>]+>/i';corrects the problem; however, this illustrates why you shouldn’t use regex to parse HTML.You wrote:
If the text you’re referring to is actually HTML, then there are better alternatives to using regex for this.
Update
I believe this is what you’re looking for.
There’s no need for a separate
youtube()function.If you want to replace more than one image, use
preg_replace_all()instead ofpreg_replace().