首页 > 解决方案 > 如何使用正则表达式匹配开始和结束标签以及它们之间的任何内容,包括空格?

问题描述

我的数据库中存储了 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);

但是如何用数据库中的简码替换该值。

标签: phphtmlregexwordpress

解决方案


运行这个正则表达式:<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']

您可以在此处阅读有关捕获组和反向引用的信息。


推荐阅读