【问题标题】:Find All images on a Page using preg_replace使用 preg_replace 查找页面上的所有图像
【发布时间】:2012-11-24 12:53:17
【问题描述】:

如何使用“preg_replace”找到所有图片链接?我很难理解如何实现正则表达式

到目前为止我所尝试的:

$pattern = '~(http://pics.-[^0-9]*.jpg)(http://pics.-[^0-9]*.jpg)(</a>)~';
$result = preg_replace($pattern, '$2', $content);

【问题讨论】:

  • 为了更好地理解添加示例...您当前拥有的一个示例链接和您想要的一个...
  • 正则表达式并不是万能的终极解决方案。
  • @nhahtdh 是对的,您应该使用 SAX 或 DOM 和 XPath。

标签: php regex preg-replace


【解决方案1】:

preg_replace(),顾名思义,替换了一些东西。你想使用preg_match_all()

<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[2] . "\n";
    echo "part 3: " . $val[3] . "\n";
    echo "part 4: " . $val[4] . "\n\n";
}

【讨论】:

    【解决方案2】:

    另一种从网页中查找所有图片链接的简单方法,使用简单的 html dom 解析器

    // 从 URL 或文件创建 DOM

    $html = file_get_html('http://www.google.com/');
    

    // 查找所有图片

    foreach($html->find('img') as $element) 
    echo $element->src . '<br>';
    

    这是从任何网页获取所有图片链接的简单方法。

    【讨论】:

    • +1。如果您对网页中更复杂的结构感兴趣,这绝对是您的最佳选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多