[英]PHP find string of substring using Regex
我有一个要在项目中使用的网页源代码。 我想在此代码中使用图像链接。 因此,我想使用PHP中的regex到达此链接。
而已:
img src =“ http://imagelinkhere.com” class =“ image”
只有这样的一行。 我的逻辑是让
=”
和
“ class =” image“
字符。
我该如何使用REGEX? 非常感谢你。
不要将Regex
用于HTML ..试试DomDocument
$html = '<html><img src="http://imagelinkhere.com" class="image" /></html>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$img = $dom->getElementsByTagName("img");
foreach ( $img as $v ) {
if ($v->getAttribute("class") == "image")
print($v->getAttribute("src"));
}
产量
http://imagelinkhere.com
运用
.*="(.*)?" .*
使用preg replace时,只给您第一个正则表达式组(\\ 1)中的URL。
如此完整,看起来像
$str='img src="http://imagelinkhere.com" class="image"';
$str=preg_replace('.*="(.*)?" .*','$1',$str);
echo $str;
- >
http://imagelinkhere.com
编辑:或者只是按照巴巴的建议,并使用DOM分析器。 我会记得,使用regex解析html时,它会让您头疼。
preg_match("/(http://+.*?")/",$text,$matches);
var_dump($matches);
链接将在$ matches中。
有几种方法可以这样做:
1.您可以将SimpleHTML Dom Parser与简单HTML一起使用
2.你也可以使用preg_match
$foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" class="image" />';
$array = array();
preg_match( '/src="([^"]*)"/i', $foo, $array ) ;
看到这个线程
我能听到蹄声,所以我使用DOM解析代替了正则表达式。
$dom = new DOMDocument();
$dom->loadHTMLFile('path/to/your/file.html');
foreach ($dom->getElementsByTagName('img') as $img)
{
if ($img->hasAttribute('class') && $img->getAttribute('class') == 'image')
{
echo $img->getAttribute('src');
}
}
这只会回显带有class="image"
的img标签的src属性
尝试使用preg_match_all,如下所示:
preg_match_all('/img src="([^"]*)"/', $source, $images);
那应该将所有图像的URL放在$images
变量中。 正则表达式的作用是找到代码中的所有img src
位,并匹配引号之间的位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.