如何使用“preg_replace”查找所有图像链接?我很难理解如何实现正则表达式
到目前为止我尝试过的事情:
$pattern = '~(http://pics.-[^0-9]*.jpg)(http://pics.-[^0-9]*.jpg)(</a>)~';
$result = preg_replace($pattern, '$2', $content);
答案 0 :(得分: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";
}
答案 1 :(得分:2)
另一种从网页链接查找所有图片链接的简单方法,使用简单的html dom解析器
//从URL或文件
创建DOM$html = file_get_html('http://www.google.com/');
//查找所有图片
foreach($html->find('img') as $element)
echo $element->src . '<br>';
这是从任何网页获取所有图片链接的简单方法。