How to substitute different words into links with preg_replace?

Wrote the code which names to replace the html links in the text, but in the conclusion it says the same names. For example, I want to get: Welcome, @user. Welcome, @user2. It outputs: Welcome, @user2. Welcome, @user2.

<?php
$re = '/@[a-zA-Z0-9]+/m'; // Pattern to replace
$str = 'Welcome, @user! Welcome, @user2!'; // Text to replace user names

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

foreach ($matches as $a) {
 $content_for_replace = $a[0];
 $content_to_replace = '<a href="profile.php?user='$b'">'.$b.'</a>';

 $str = preg_replace($re, '<a href="">'.$a[0].'</a>', $a[0]);
}

echo $str;
?>


I understand that during this cycle, it replaces the pattern all matches, but I can't figure out how to fix it?
March 23rd 20 at 19:34
2 answers
March 23rd 20 at 19:36
Solution
Look at the code and think that your code does actually. See the debugger the contents of variables or corny print them.

1) You match do first (don't know why, but Oh well, not that question).
2) Then go around the results.
3) Then ignore what you found and for all the same regular season that, in paragraph 1, replace everything in line on befroe a coincidence.

The result is absolutely logical. Correct the logic to replace the body of the loop only one relevant match.

Using preg_replace to do this corny easier than match + cycle on it. And then there are preg_replace_callback if you just replace missing.
Oh, I realized that just created a bike - Noe_Rosenba commented on March 23rd 20 at 19:39
March 23rd 20 at 19:38
Solution
But why so difficult with the cycle? You can just using preg_replace to replace.
$str = 'Welcome, @user! Welcome, @user2!';
echo preg_replace('/@([a-z0-9]+)/i', '<a href="profile.php?user=$1" >@$1</a>', $str);

PS you Have in the code I'd used the $b variable and in line with it missed the point for concatenation of strings
Well, if you do so, you get: href=".@user." as I wrote it in single quotes - Noe_Rosenba commented on March 23rd 20 at 19:41

Find more questions by tags PHP