function function_to_makeItClear($string) {
$string = strtolower($string);
$string = str_ireplace(' ', '-', $string);
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
function betterId($match){
$escape = str_split(strip_tags($match[2]), 20);
$id = strlen($escape[0]) >=5 ? function_to_makeItClear($escape[0]) : str_shuffle('AnyWordsHere');
return '<h'.$match[1].' id="'.$id.'">'.$match[2].'</h'.$match[1].'>';
}
return preg_replace_callback('#<h([1-6]).*?>(.*?)<\/h[1-6]>#si', 'betterId', $texte);
这是我要转换的文字
<p>Paragraph one is okay </p> <h2>This will work without problem</h2> <p>Paragraph two is okay </p> <h2><a href="#">This heading has anchor</a></h2> <p>Paragraph one is okay </p> <h2> This heading start with space</h2> <p>Paragraph two is okay </p> <h3>1. <a href="https://www.example1.com/">This wont work</a></h3> <p>Paragraph one is okay </p> <h3>2. <a href="https://www.example2.com/">Not working</a></h3> <p>Paragraph two is okay </p> <h3>3. Neither this one</h3> <h3>But this works again</h3>
我想要这样的东西:
<p>Paragraph one is okay </p> <h2 id="this-will-work">This will work without problem</h2> <p>Paragraph two is okay </p> <h2 id="this-heading-has"><a href="#">This heading has anchor</a></h2> <p>Paragraph one is okay </p> <h2 id="this-heading-start"> This heading start with space</h2> <p>Paragraph two is okay </p> <h3 id="this-wont-work">1. <a href="https://www.example1.com/">This wont work</a></h3> <p>Paragraph one is okay </p> <h3 id="not-working">2. <a href="https://www.example2.com/">Not working</a></h3> <p>Paragraph two is okay </p> <h3 id="neighter-this-one">3. Neither this one</h3> <h3 id="but-this-works">But this works again</h3>
任何帮助将不胜感激更新:
实际上,我使用的是@mickmackusa的DOMParser解决方案,效果很好,但在某些情况下效果也不佳,在这种情况下,我必须自己手动添加ID