-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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There is no need for any capture groups. $0 will work just fine. And no need to answer duplicate questions for that matter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.