在正则表达式中使用反向引用

时间:2015-02-02 10:42:11

标签: php regex preg-replace

我有一个php函数,可以将Facebook帖子作为文本返回。但是,我希望所有#-hashtags都可以点击并引用http://www.facebook/hashtags/ {the-hashtag}。我试着用下面的preg_replace做这个,但显然我做错了什么:

$postMessage = preg_replace('/#[^(\s|\p{P})]*', '<a href="https://www.facebook.com/hashtag/$1" title="$1"></a>', $postMessage);

这会输出预期的链接,因此正则表达式似乎正确,但输出如下:

<a href="https://www.facebook.com/hashtag/" title=""></a>

所以我很确定我在后面引用时做错了,但我不完全确定是什么。

(旁边的问题,是preg_replace中不需要的global参数吗?我习惯在JS中使用它。)

$postMessage的一个例子:

Android Wear testen doen we met de Sony #Smartwatch3. Binnenkort volgt een uitgebreide review op de website ;-)

输出应为:

Android Wear testen doen we met de Sony <a href="https://www.facebook.com/hashtag/smartwatch3" title="Smartwatch3">#Smartwatch3</a>. Binnenkort volgt een uitgebreide review op de website ;-)

2 个答案:

答案 0 :(得分:2)

<强>正则表达式:

#([^\p{P}\s]*)

[^\p{P}\s]*匹配任何字符,但不匹配标点或空格,零次或多次。

替换字符串:

<a href="https://www.facebook.com/hashtag/$1" title="$1">#$1</a>

DEMO

PHP代码将是,

$re = "/#([^\\p{P}\\s]*)/m";
$str = "Android Wear testen doen we met de Sony #Smartwatch3. Binnenkort volgt een uitgebreide review op de website ;-)\n\n";
$subst = "<a href=\"https://www.facebook.com/hashtag/$1\" title=\"$1\">#$1</a>";

$result = preg_replace($re, $subst, $str);

答案 1 :(得分:1)

#([^\s\p{P}]*)\S+

正确分组你的正则表达式。它正在工作。参见演示。

https://regex101.com/r/vD5iH9/39

相关问题