0

I have a php function that returns a Facebook post as text. However, I want all the #-hashtags to be clickable and to refer to http://www.facebook/hashtags/{the-hashtag}. I tried doing this with the following preg_replace, but apparently I'm doing something wrong:

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

This outputs links where expected, so the regex seems right, but the output looks like this:

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

So I'm pretty sure I'm doing something wrong with the back reference, but I'm not entirely sure what.

(Side question, is the global parameter not necessary in preg_replace? I'm used to using it in JS.)

An example of $postMessage:

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

Output should be:

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 ;-)
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239

2 Answers2

2

Regex:

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

[^\p{P}\s]* matches any character but not of punctuations or spaces , zero or more times.

Replacement string:

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

DEMO

PHP code would be,

$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);
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1
#([^\s\p{P}]*)\S+

Just group your regex correclty.Its working.See demo.

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

vks
  • 67,027
  • 10
  • 91
  • 124