开发者

find image with specific src using preg_replace

开发者 https://www.devze.com 2023-04-13 05:15 出处:网络
I have some text with images within it. I want to replace specific images within the text with something else.

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 开发者_StackOverflow中文版to change in the regex to do the above?


Your regex is looking for <img src=, but there is a class attribute between img and src. Using $find= '/<img.*src=[^>]+>/i'; corrects the problem; however, this illustrates why you shouldn’t use regex to parse HTML.

You wrote:

I have some text with images within it.

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.

<?php
function replacelink($text) {
    $replace = '<iframe title="$2" class="youtube-player" type="text/html" width="576" height="400" <iframe title="$2" class="youtube-player" type="text/html" width="576" height="400" src="http://www.youtube.com/embed/$2" frameborder="0"></iframe>';
    $find = '/(<img.*?alt="([\da-z]+)".*?>)/i';
    return preg_replace($find, $replace, $text);
}

$imagestr = '<img class="mceItem" src="http://img.youtube.com/vi/1MsVzAkmds0/default.jpg" alt="1MsVzAkmds0">';
echo replacelink($imagestr);
?>

There’s no need for a separate youtube() function.

If you want to replace more than one image, use preg_replace_all() instead of preg_replace().


The following regex would get all the images with a specific url. I not sure if this is what you wanted.

<img [^>]*?src="url"[^>]*?>

Previous anwser would fail if there were more than one image.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号