PHP:使用preg_replace_callback()为标题生成ID在某些情况下不起作用[关闭]

问题描述 投票:-1回答:1
我有一个使用Tinymce TOC的客户,但不喜欢该插件添加到标题(h2-h3)的随机ID。创建一个脚本会自动创建这些ID,并在每次编辑文章并将其添加到漫画时将其添加到标题的含义是什么。我以为我可以使用preg_replace_callback()做到这一点,但是当我使用该函数时,我意识到在某些情况下它不起作用。例如,如果H2 / h3以空格,数字等开头,则不起作用。这是我使用PHP进行的操作,在某些情况下可以使用:

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

php regex preg-replace-callback
1个回答
0
投票
使用DOMDocument从可靠的html中可靠地提取标题标记。
© www.soinside.com 2019 - 2024. All rights reserved.