add_anchors($content);
}
return $content;
}
/**
* Replace all headings with an anchor
*
* @param string $text Text to be searched in.
* @return string
*/
public static function add_anchors($text)
{
// Search for headlines.
$pattern = '#]+)?>(.+?)#is';
preg_match_all($pattern, $text, $headlines, PREG_OFFSET_CAPTURE);
$offset = 0;
$used_anchors = [];
if ($headlines) {
foreach ($headlines[2] as $match) {
list($headline, $pos) = $match;
if (strlen($headline)) {
$anchor = \sanitize_title($headline);
// Ensure unique anchor IDs for duplicate headings.
if (isset($used_anchors[$anchor])) {
$used_anchors[$anchor]++;
$anchor .= '-' . $used_anchors[$anchor];
} else {
$used_anchors[$anchor] = 1;
}
$icon = '';
$text = substr_replace($text, $icon, $offset + $pos, 0); // Insert after H tag.
$offset += strlen($icon);
}
}
}
return $text;
}
}
}
new AddAnchorLinks();