-3

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

到目前为止我已经尝试过:

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

2 回答 2

3

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";
}
于 2012-11-24T13:00:32.853 回答
2

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

// 从 URL 或文件创建 DOM

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

// 查找所有图像

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

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

于 2012-11-24T13:23:52.787 回答