2

So, I have got a preg_replace function that should replace the following pattern: Usernames with an @-character in front of them.

I have got the usernames in a multi dimensonal array called allMembers() and the regex to replace any word with a @-character and spaces around it:

/\B@[a-z-]+\s/

But how do I run the usernames contained in the array through the preg_replace function? So, just one replacement for multiple patterns.

$mentionPattern = "/\B@[ USERNAMES FROM ARRAY ALLMEMBERS HERE ]+\s/";                                
$mentionReplace = "<a class='userMention'>$0</a>";
preg_replace($mentionPattern, $mentionReplace, $text);

Example:

Users on my website: John, Harry, Peter

Whenever someone adds a message like "bla bla @John bla bla", the "@John" part should be replaced by something else. Replacement thus depends on the use of @ and an existing username (that I have inside an array).

1
  • 3
    Join them in a grouped altern|ative|list, don't forget to preg_quote each. Commented Feb 1, 2015 at 15:00

1 Answer 1

2

A good way is to use preg_replace_callback. The advantage is that you avoid to use a pattern with an alternation that is slow (in particular if you have a lot of users):

$result = preg_replace_callback('~@(\w+)~', function ($m) use ($usernames) {
    return (in_array($usernames, $m[1])) ? '<a ...>' . $m[0] . '</a>'
                                         : $m[0];
}, $text); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Jonny5: it's only an example, you can easily change the pattern if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.