
正则表达式匹配:避免过度匹配
在提取HTML标签内的标题信息时,避免过度匹配至关重要。 例如,如果目标文本包含以下标签:
<p>李明:</p>
<p>tittle: </p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
<p>my brief:xxxxx</p>
<p></p>
我们希望仅提取tittle:及其后的内容,直到下一个<p></p>标签。 错误的正则表达式,例如/\<p>[\s\s]+\tittle\:[\s\s]+\//</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1591">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680267270309.png" alt="智标领航">
</a>
<div class="aritcle_card_info">
<a href="/ai/1591">智标领航</a>
<p>专注招投标业务流程的AI助手,智能、高效、精准、易用!</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="智标领航">
<span>117</span>
</div>
</div>
<a href="/ai/1591" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="智标领航">
</a>
</div>
,由于[\s\s]+匹配任意字符(包括空格和换行符),会导致匹配范围过大。
更精准的匹配方法是避免使用[\s\s]+,而是使用[^<]+,匹配除<以外的任意字符,直到遇到下一个<标签。 这样可以有效地限制匹配范围。
改进后的正则表达式示例:
<code class="php">$str = '<p>李明:</p><p>tittle: </p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p><p>my brief:xxxxx</p><p>';
preg_match('/<p>([^<]+tittle:[^<]+)<\/p>/', $str, $m);
var_dump($m);</code>此代码片段将精准匹配<p></p>标签内包含tittle:的内容,并排除前后多余的标签和字符。 请注意,这仍然依赖于目标文本的结构。 对于更复杂的HTML结构,建议使用DOM解析器进行处理,以确保更可靠的匹配结果。
以上就是如何精准匹配HTML标签内的标题信息?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号