[英]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.