H2 tag auto ID in php string
I'm trying to write a wordpress filter that autopar开发者_JS百科ses the content and takes the following:
<h2>lesson 1 bannanas</h2>
and replaces it with
<h2 id="lesson-1-bannanas">lesson 1 bannanas</h2>
So that I can then link people directly to sections of a page or blogpost. How would I do this without resorting to something as heavy as DOMDocument?
If you have a coherent input like that, then you can use regular expressions. In this case it's both very acceptable and simple:
$html = preg_replace_callback("#<(h[1-6])>(.*?)</\\1>#", "retitle", $html);
function retitle($match) {
list($_unused, $h2, $title) = $match;
$id = strtolower(strtr($title, " .", "--"));
return "<$h2 id='$id'>$title</$h2>";
}
The id conversion needs a bit more work. And to make the regex more reliable the innter text match pattern (.*?)
could be written as ([^<>]*)
for example.
I have created a php
function to adding id to all h2
tags automatically.
function h2slug($text) {
preg_match_all("|<h2(.*)>(.*)</[^>]+>|U", $text, $out, PREG_SET_ORDER);
foreach ($out as $header) {
$slug = slug($header[2]);
$header[1] = preg_replace('/(?<!\S\W\w\s)(\s?)id(\s?)="(\w*\W*)"/', '' , $header[1]);
$text = str_replace($header[0], '<h2 id="'. $slug .'"'. $header[1] .'>'. $header[2] .'</h2>', $text);
}
return $text;
}
Using:
<?php echo h2slug('<h2>Lesson 1 bannanas.</h2>'); ?>
Export:
<h2 id="lesson-1-bannanas">Lesson 1 bannanas.</h2>
Another way (that actually is quite simple, although it resorts to dom manipulation) is using jQuery to add a id, thats equal to the content of the h2
You could use str_replace to replace the opening h2 tag with one containing your ID
$tag = '<h2>My content</h2>';
$tag = str_replace('<h2>', '<h2 id = "an id">', $tag);
echo $tag;
精彩评论