doujiene2845 2018-04-24 09:30
浏览 42

只匹配正则表达式中前两次出现 - PHP

I'm trying to replace text with a link. The regex I now have, replaces all matches but I only want to replace the first two occurrences.

It should replace all occurrences of find me with a link, except when it is located in a or tag.

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

My current regex:

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

My dummy content:

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>

My 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);

Hope a fellow programmer can help me out :)

  • 写回答

1条回答 默认 最新

  • dongqijuan3786 2018-04-24 14:51
    关注

    Fixed it by using the (for me) unknown $limit parameter .

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

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

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么