[英]Converting html headings with php regex
我有帶有html標記文本的字符串:
<p>Some random text</p>
<h2>This is a heading</h2>
<p>More text</p>
我想將其轉換為類似的內容:
<p>Some random text</p>
<h2 id="This_is_a_heading">This is a heading</h2>
<p>More text</p>
這個簡單的代碼幾乎可以做到:
$patterns = array('#(<h2>)(.*)(</h2>)#i');
$replace = array('<h2 id="\2">\2</h2>');
$text = preg_replace($patterns, $replace, $text);
但是我仍然不知道如何在id
屬性中用underscores
替換whitespaces
,最后在$text
得到了這個:
<p>Some random text</p>
<h2 id="This is a heading">This is a heading</h2>
<p>More text</p>
我已經嘗試搜索了幾個小時,但是沒有運氣。 請幫忙。
使用HTML解析器
這是解析HTML的推薦方法。 除非您完全確定HTML字符串的格式是完全固定的,否則正則表達式處理不足,您必須使用HTML解析器。 這是使用PHP附帶的DOMDocument
類的解決方案:
$dom = new DOMDocument;
$errorState = libxml_use_internal_errors(true);
$dom->loadHTML($text);
foreach ($dom->getElementsByTagName('h2') as $tag) {
$nodeValue = (string) $tag->nodeValue;
$id = str_replace(' ', '_', $nodeValue);
$tag->setAttribute('id', $id);
}
echo $dom->saveHTML();
使用正則表達式
對於簡單的替換,DOM解析器可能會顯得過大。 如果您不太在意結果的准確性,則可以使用正則表達式來完成任務。 請注意,如果標記之間包含其他屬性或額外標簽,則可能會中斷此操作。
在這種情況下,您的preg_replace()
將無法工作,因為它無法修改反向引用。 使用preg_replace_callback()
代替:
$text = preg_replace_callback('#(<h2>)(.*)(</h2>)#i', function ($m) {
$id = str_replace(' ', '_',$m[2]);
return "<h2 id=\"$id\"></h2>";
}, $text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.