php - 如何使用正则表达式匹配开始和结束标签以及它们之间的任何内容,包括空格?
问题描述
我的数据库中存储了 html 内容,我需要做的是我必须获取此内容并匹配锚标记并用任何字符串替换该锚标记。
假设我在我的 wordpress 数据库中存储了以下 html。
<h3>Complications</h3>
<p><strong>The three most common serious gastric sleeve complications</strong> are:</p>
<ul>
<li>
<a href="https://insights.ovid.com/pubmed?pmid=28938270" target="_blank">3</a>
<span><a href="javascript:;" class="list_expand">Staple line leaks</a> - 2.1% of patients on average (between 1.09% and 4.66%, depending on the study) experience staple line leaks (<a href="#reference-box">9</a>) (<a href="#reference-box">10</a>)</span>
<div class="list_expand_content blockquote"></div>
</li>
<li>
<span><a href="javascript:;" class="list_expand">Bleeding</a> - 1.2% of patients (<a href="#reference-box">11</a>)</span>
<div class="list_expand_content blockquote"></div>
</li>
<li>
<span><a href="javascript:;" class="list_expand">Stenosis/Strictures</a> - 0.6% of patients (<a href="#reference-box">12</a>)</span>
<div class="list_expand_content blockquote"></div>
</li>
</ul>
我需要做的是我必须匹配锚标签,就像
<a anthing goes here>[0-999]</a>
并用短代码替换该锚标签,例如 [ref link= '链接在每个锚标签内' number='number 包装在起始和结束锚标签之间']。
我编写了以下代码来匹配值并获取值。
preg_match_all('/<a[^>]+>(\d{1,3})<\/a>/',$content,$matches, PREG_PATTERN_ORDER);
但是如何用数据库中的简码替换该值。
解决方案
运行这个正则表达式:<a[^>]+href="([^"]+?)"[^>]+>(\d{1,3})<\/a>
有了这个替换:[ref link='$1' number='$2']
如您所见,这将替换:
<a href="https://insights.ovid.com/pubmed?pmid=28938270" target="_blank">3</a>
有了这个:
[ref link='https://insights.ovid.com/pubmed?pmid=28938270' number='3']
您可以在此处阅读有关捕获组和反向引用的信息。
推荐阅读
- python - 我正在尝试使用 python rewrite 制作一个不和谐的机器人,它每 24 小时或每天在特定时间更改频道权限
- javascript - 如何使用 Firefox 扩展触发此事件“browser.browserAction.onClicked.addListener()”?
- python-3.x - 如何正确地将字符串转换为列表
- laravel - 登录后laravel 7 csrf令牌更改
- python - SendBird 错误 400403 无效值:JSON 正文
- python - 定义和求解无冗余方程(Python)
- scala - 使用功能构造的组合批处理
- flutter - Flutter - Ontap InkWell 在 Stack 中不起作用
- c# - C# 应用程序是否可以读取其他应用程序发送的通知并相应地执行操作?
- swift - videoGravity resizeAspectFill 不起作用 - Swift - AVFoundation