【发布时间】:2014-02-16 18:32:16
【问题描述】:
我有带有 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 属性中将whitespaces 替换为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。
标签: php html regex preg-replace