简体   繁体   English

PHP将ID属性添加到标题

[英]PHP Adding ID Attribute to Headings

I am trying to parse HTML headers for my pages and add an ID to match the content. 我正在尝试解析页面的HTML标头并添加ID以匹配内容。 I've managed to do it with find and replace but it fails when any additional HTML attributes are present... 我已经设法通过查找和替换来做到这一点,但是当存在任何其他HTML属性时,它就会失败...

Heres whats in the array of headers to change 这是要更改的标头数组中的内容

[
    'find' => sprintf('<h%u>%s</h%u>', $level, $title, $level),
    'replace' => sprintf('<h%u id="%s">%s</h%u>', $level, slugify($title), $title, $level),
    'slug' => slugify($title)
]

Later on the replace is then done... 稍后替换完成...

foreach ($parsed_content as $fix) {
    $content = str_replace($fix['find'], $fix['replace'], $content);
}

This isn't the best way to do it I know but it was just a test, now to make it work properly I think I just need to use a regular expression instead of a standard str_replace call. 我知道这不是最好的方法,但这只是一个测试,现在要使其正常运行,我想我只需要使用正则表达式而不是标准的str_replace调用即可。

I am using DOMDocument, would there be an alternative way to do it in there maybe? 我正在使用DOMDocument,也许在那里有替代方法吗?

Edit: I'm trying to use xpath to mainipulate the html. 编辑:我正在尝试使用xpath来处理html。 I've got a simple loop to get the data but i'm not sure how to apply the code to the actual docoument. 我有一个简单的循环来获取数据,但是我不确定如何将代码应用于实际文档。 Any ideas? 有任何想法吗? Heres what I have atm 这是我的atm

$dom = new DOMDocument;
$dom->loadHTML($the_dom);
$xpath = new DOMXPath($dom);

$elements = $xpath->query('(//h1|//h2|//h3|//h4|//h5)');

foreach ($elements as $index => $element) {

    $element->setAttribute('id', sanitize_title($element->textContent));
    pr($element);

}

My suggestion would be to use JS to accomplish this. 我的建议是使用JS完成此操作。

First, set JS variables with the PHP variables' values: 首先,使用PHP变量的值设置JS变量:

var level = <?= $level ?>; // inject PHP into JS
var title = <?= $title ?>;

Then, use JS (or jQuery) to replace the content: 然后,使用JS(或jQuery)替换内容:

$("h" + level).text(title);

I think this method of manipulating the DOM from the client-side is easier than using regex from a server-side language. 我认为从客户端操作DOM的这种方法比从服务器端语言使用regex容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM