簡體   English   中英

使用PHP preg_replace將文本附加到使用正則表達式找到的模式

[英]Using PHP preg_replace to append text to pattern found with regex

我想在所有標簽img之前和之后添加標簽div。

所以我有

<img src=%random url image% />

並且應該替換為

<div class="demo"><img src=%random url image% /></div>

我可以用preg_replace嗎?

$string = %page source code%;
$find = array("/<img(.*?)\/>/");
$replace = array('<div class="demo">'.$find[0].'</div>');
$result = preg_replace($find, $replace, $string);

但這不起作用:/

解析HTML的更好方法是使用PHP的DOMDocumentDOMXPath類。 您可以使用XPath查找所有圖像,然后在它們周圍添加一個div,如本示例所示:

$html = '<div><img src="http://x.com" /><span>xyz</span><a href="http://example.com"><img src="http://example.com" /></a></div>';
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXpath($doc);
$images = $xpath->query('//img');
foreach ($images as $image) {
    $div = $doc->createElement('div');
    $div->setAttribute('class', 'demo');
    $image->parentNode->replaceChild($div, $image);
    $div->appendChild($image);
}
echo $doc->saveHTML();

輸出:

<div>
    <div class="demo"><img src="http://x.com"></div>
    <span>xyz</span>
    <a href="http://example.com">
        <div class="demo"><img src="http://example.com"></div>
    </a>
</div>

3v4l.org上的演示

暫無
暫無

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

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