用正则表达式替换图像 [英] Replace images with regular expressions

查看:101
本文介绍了用正则表达式替换图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这个字符串上找到并做一些操作:

I want to find and do some operations on this string:

<img src="images/video.png" border="0" alt="60" />




  1. 查找上下文中的每一个出现

  2. 检索alt属性(在本例中为60)并使用此数字

  3. 替换整个图像

我一直在玩正则表达式,但它显然还没有用:

I've been playing around with regular expressions but it obviously doesn't work yet:

    if (preg_match_all('<img src="images/video.png" border="0" alt="[^"]*">', $content, $regs)) {
    for($i=0;$i<count($regs[0]);$i++){

        echo $regs[0][$i] . "<br>";
        $id = preg_replace('alt="[^"]*"', "$1", $regs[0][$i]);
        echo "The id: " . $id . "<br>";

    }
}


推荐答案

如何使用 PHP Simple HTML DOM Parser 解析DOM

您可以从此处下载脚本: http://sourceforge.net/projects/simplehtmldom / files /

You can download the script from here: http://sourceforge.net/projects/simplehtmldom/files/

如果您将该脚本加载到当前脚本中,如下所示:

If you load that script in to your current script like this:

include_once("simple_html_dom.php");

然后你可以循环浏览HTML中的所有图像并用它们做你想做的事情:

And then you can loop through all images in your HTML and do what you want with them:

$html = "Your HTML code";

foreach($html->find('img') as $element) {

    // Do something with the alt text
    $alt_text = $element->alt;

    // Replace the image
    $element->src = 'new_src';
    $element->alt = 'new_alt';

}






使用库:


Without using a library:

// Load the HTML
$html = "Your HTML code";
$dom = new DOMDocument();
$dom->loadHTML($html);

// Loop through all images
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {

  // Do something with the alt
  $alt = $image->getAttribute('alt');

  // Replace the image
  $image->setAttribute("src", "new_src");
  $image->setAttribute("alt", "new_alt");

}

// Get the new HTML string
$html = $dom->saveHTML();

这篇关于用正则表达式替换图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆