我有串HTML標記的文字:用PHP正則表達式轉換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);
但我仍然不知道如何與underscores
在更換屬性,我結束了這$text
:
<p>Some random text</p>
<h2 id="This is a heading">This is a heading</h2>
<p>More text</p>
我試圖尋找現在的幾個小時,但沒有運氣。請幫忙。
您最好用html解析器。注意,如果你想在替換上運行另一個替換,你需要preg_replace_callback。 – Jerry