user3745594 user3745594 - 4 months ago 16
PHP Question

str_replace inside foreach loop not replacing

MY CODE :

$string = "@admin BLA BLA @mark BLA BLA BLA @koko BLA BLA";
preg_match_all("/(@\w+)/", $string, $matches);

foreach ($matches[0] as $usernames) {
$user = (" SELECT * FROM user WHERE username = '" . $usernames . "' ");
while ($row = mysql_fetch_array($user)) {
$string = str_replace($usernames, $row["userid"], $string);
}
}
echo $string;


I am trying to replace all
usernames
after
@
with their associated user id , but when I print the text, the output is same as the original text.

output :
@admin BLA BLA @mark BLA BLA BLA @koko BLA BLA

Answer

Your SQL query will be something like SELECT * FROM user WHERE username = '@admin' - which may be not your expectation.

Try this fix:

$user = (" SELECT * FROM user WHERE username = '" . substr($usernames, 1) . "' ");

Hope that it can help you :)

Comments