【问题标题】:Only match first two occurences in regex - PHP仅匹配正则表达式中的前两次出现 - PHP
【发布时间】:2018-04-24 09:30:59
【问题描述】:

我正在尝试用链接替换文本。我现在拥有的正则表达式替换了所有匹配项,但我只想替换前两个匹配项。

它应该用链接替换所有出现的find me,除非它位于或标记中。

https://regex101.com/r/6R2ydW/1 http://www.phpliveregex.com/p/nLI

我当前的正则表达式:

/<(a|h[1-6])[^>]*>(?:[a-zA-Z0-9\s\'\-\.,]|(?:<(.*)>.*<\/\1>))*<\/(a|h[1-6])>(*SKIP)(*FAIL)|\b(Find Me)\b(?=[^>]*(?:<|$))/ig

我的虚拟内容:

Lorem ipsum find me and skip when 
<b>find me</b> is inside a link tag 
like this find me
<h1>find me in the title</h1>
<a href="#">here you can find me too</a>.
<h2 class="heading">Lorem Ipsum dolor find me here too</h2>
<table>
  <tr><td>Cell 1 a</td><td>Find me</td></tr>
  <tr><td>Cell 2 with find me</td><td><a href="#foo">Find me</a></td></tr>
</table>
<h3 class="heading">Duomo Di find me San Martino</h3>
<p>FIND ME as well</p>

我的 PHP preg_replace:

$text = 'Lorem ipsum find me and skip when 
    <b>find me</b> is inside a link tag 
    like this find me
    <h1>find me in the title</h1>
    <a href="#">here you can find me too</a>.
    <h2 class="heading">Lorem Ipsum dolor find me here too</h2>
    <table>
      <tr><td>Cell 1 a</td><td>Find me</td></tr>
      <tr><td>Cell 2 with find me</td><td><a href="#foo">Find me</a></td></tr>
    </table>
    <h3 class="heading">Duomo Di find me San Martino</h3>
    <p>FIND ME as well</p>';

$regex = "/<(a|h[1-6])[^>]*>(?:[a-zA-Z0-9\s\'\-\.,]|(?:<(.*)>.*<\/\1>))*<\/(a|h[1-6])>(*SKIP)(*FAIL)|\b(" . preg_quote('find me') . ")\b(?=[^>]*(?:<|$))/i";

$text = preg_replace($regex, sprintf('<a href="%s">$4</a>', 'http://example.com'), $text);

希望其他程序员可以帮助我:)

【问题讨论】:

    标签: php regex


    【解决方案1】:

    通过使用(对我而言)未知的$limit 参数修复它。

    $text = preg_replace($regex, sprintf('&lt;a href="%s"&gt;$4&lt;/a&gt;', 'http://example.com'), $text, $limit = 2);

    http://php.net/manual/en/function.preg-replace.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2015-09-27
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多