簡體   English   中英

PHP使用正則表達式查找子字符串

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM