【问题标题】:get first 10 characters of matched string --- PHP regex获取匹配字符串的前 10 个字符 --- PHP 正则表达式
【发布时间】:2016-08-22 17:47:07
【问题描述】:

在我的网站中,用户可以提供带有双星的链接,例如:**http://www.google.com** 我想使用preg_replace() 突出显示此链接。我能够捕捉到确切的链接,但是我希望将此链接的前 10 个字符放在 <a></a> 标签的中间。

代码如下:

$str = "http://www.example.com/dnvjndjnvjd";
$str = preg_replace('/\*\*(\S+)\*\*/', '<a href="$1">?#right there i want first 10 chracter of $1</a>', $str);

【问题讨论】:

  • 不必复杂,使用substr()
  • 改为替换$str并输出?
  • 使用 preg_replace_callback 并在匿名函数中修剪你的匹配。
  • 有几种方法可以做到这一点。也许eval.in/627121
  • @JayBlanchard 我应该如何在$1上使用它

标签: php regex preg-replace


【解决方案1】:

我认为最好的方法是 @chris85 说: $str = '**http://example.com/dnvjndjnvjd**'; echo preg_replace('/\*{2}([^\*]{10}).*\*{2}/', '$1', $str);

【讨论】:

    【解决方案2】:

    所以只需在一个捕获组中捕获整个事物(替换为 $1)并有一个只捕获前 10 个的子组(替换为 $2):

    $str = preg_replace('/\*\*((\S{10})\S*)\*\*/', '<a href="$1">$2</a>', $str);
    

    Debuggex Demo

    但请记住,只有 10 个字符的多个 http://www.domain.com 样式条目,您只会得到 http://www,这不是很具描述性。

    【讨论】:

      【解决方案3】:

      使用preg_replace_callback():

      <?php
      
      $string = "There is an URL in the middle of nowhere: **http://www.example.com/dnvjndjnvjd** and here's another one **http://www.example.com/ddadadada**";
      
      $regex = '~\*{2}(https?://(?:www\.)?(\S+))\*{2}~';
      
      $string = preg_replace_callback($regex,
          function($match) {
              return "<a href='{$match[1]}'>" . substr($match[2], 0, 10) . "</a>";
          },
          $string);
      
      echo $string;
      ?>
      


      a demo on ideone.com

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-05
        • 2013-12-25
        相关资源
        最近更新 更多