得到匹配字符串的前10个字符--- PHP正则表达式

时间:2016-08-22 17:47:08

标签: php regex preg-replace

在我的网站中,用户可以提供双星的链接,例如:**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);

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

这样的东西?

<?php
$str = "The magic of regex: **http://www.wizards.net/abracadabra**  
can be nerdy stuff **http://www.muggles.com/technology**";
$pattern = '/\*{2}(https?:\/\/([^*]{10})[^*]*?)\*{2}/';
$replacement = '<a href="$1">$2</a>';
echo preg_replace($pattern, $replacement, $str);

输出:

The magic of regex: <a href="http://www.wizards.net/abracadabra">www.wizard</a>  
can be nerdy stuff <a href="http://www.muggles.com/technology">www.muggle</a>

答案 3 :(得分:0)

因此,只需捕获捕获组中的整个事物(替换为$1)并创建一个仅捕获前10个子组的子组(替换为$2):

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

Regular expression visualization

Debuggex Demo

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

相关问题