簡體   English   中英

正則表達式在隨機位置找到出現

[英]Regex to find occurence at random position

我正在使用正則表達式在字符串中查找兩個HTML屬性( titlestyle )並獲取該值。 在某些情況下, style屬性不存在,因此我只需要title值。

到目前為止,我已經將它用於title屬性在style屬性之前的情況,無論是否定義了style

出於某種原因,在title屬性之前定義style屬性時會發生此問題。

我在Drupal中使用這個正則表達式,所以我不太擔心HTML不一致,但屬性順序似乎有問題。

這是我到目前為止的表達方式


/<img\s{1}.*title=\"(.*)\"\s{1}.*(style=\"(.*)\"\s{1}.*)?>/siU

我在互聯網上搜索過文章但找不到合適的解決方案。 我希望有人可以幫助我。 我對它的困惑時間更長,我應該已經准備好了。

提前致謝!

正則表達式不是執行此任務的最佳工具。 請改用DOM解析器。 這是使用PHP的內置DOMDocument類的一個解決方案:

$html = <<<HTML
<img style="width:20px" title="Some Title" src="foobar.jpg" />
<img title="Some Title" src="foobar.jpg" />
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as $img)
{
    if (!$img->hasAttribute('style') && $img->hasAttribute('title'))
    {
        echo $img->getAttribute('title') . "\n";
    }
    elseif ($img->hasAttribute('style') && $img->hasAttribute('title'))
    {
        echo $img->getAttribute('style') . "\n";
        echo $img->getAttribute('title') . "\n\n";
    }
}

輸出:

width:20px
Some Title

Some Title

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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