读取标签内部并向标签添加ID

时间:2016-03-14 01:45:04

标签: php regex preg-replace

我有一个问题,我想要做以下但我无法弄清楚preg_replace如何做到这一点。我只能添加一些不读的东西然后添加。

我有一个300,000多页的网站,我们正在尝试制作一个锚文本链接侧栏。但首先我需要为所有h2标签添加一个ID,所以我有<h2>this is the title</h2>,我需要PHP自动在页面上呈现输出<h2 id="this-is-the-title">This is the title</h2>

不幸的是,所有的尝试都失败了。我试过谷歌但是搜索起来很难,因为我不确定它叫什么。

关于这是什么或代码片段的任何想法?

1 个答案:

答案 0 :(得分:0)

规则是 - 像往常一样 - no regular expression with HTML。请使用DOMDocument

首先创建一个函数来生成基于标题的id:

function value2id( $text )
{
    $retval = preg_replace( '/ +/', '-', trim( $text ) );
    if( preg_match( '/^[^a-z]/i', $retval ) ) $retval = "a$retval";
    return $retval;
}

以上函数将返回与HTML HTML兼容的ID。如果您的HTML代码版本较低,则ID中允许使用more restriction个字符。您可以根据需要修改功能。

然后,在<body>对象中加载整个旧页面(我不知道在db中是否有完整代码或只有DOMDocument),搜索所有{{1 }}和添加<h2>属性调用自定义函数:

id

现在,您可以通过以下方式打印修改过的HTML:

$dom = new DomDocument();
libxml_use_internal_errors(1);
$dom->loadHTML( $html );

foreach( $dom->getElementsByTagName( 'h2' ) as $h2 )
{
    $h2->setAttribute( 'id', value2id( $h2->nodeValue ) );
}