I have a text that contains usernames prepended with @ symbol. Example:
One day @john decided to ask @jane out.
I want to replace all occurances of the usernames with a link, for the sake of an example lets say I would want to replace @user with link-user, Example:
One day link-john decided to ask link-jane out.
This can be done with following command:
preg_replace('`@([a-zA-Z0-9]{2,15})`', 'link-$1', $text);
Additionally I would like to obtain an array of all the matches like preg_match would have done, but I am unable to, because preg_replace does not seem to provide that array. What is the most efficient way to accomplish this? I feel like doing preg_match and later preg_replace would be a waste of resources, would it not?
If you feel there is a better way to accomplish this, I would appreciate your feedback.
Thanks!
You can use preg_replace_callback:
Result:
If you are using PHP 5.3, you can make this much cleaner with anonymous functions.