-1

On my website, I have comments.

In my comment string, I find all username mentions like so (username mentions start with /u/, for example /u/felix):

preg_match_all('#/u/([a-z0-9]+)#i', $comment, $matches);

Now I have an array of usernames called $matches.

I want to then replace all username matches in $comment with something like this:

<a href="/u/felix">/u/felix</a>

I tried doing a foreach solution with a str_replace, however I run into the problem of having users that contain the usernames of other users. So if we had the users "fel", feli" and "felix, the loop would do it 3 times for "fel".

How can I do this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Felix
  • 2,532
  • 5
  • 37
  • 75

1 Answers1

1

If you don't need to extract the usernames, just replace them all at once with a single regexp:

preg_replace( '#(/u/[a-z0-9]+)#i', '<a href="$1">$1</a>', $comment );

No need to worry about similar usernames since each will be matched and replaced without affecting the others.

kmoser
  • 8,780
  • 3
  • 24
  • 40
  • There is no need for any capture groups. `$0` will work just fine. And no need to answer duplicate questions for that matter. – mickmackusa Jun 02 '20 at 05:11