Joshua Joshua - 19 days ago 6
PHP Question

PHP mention script

I'm working on a mention script that gets an users profile link when it is being mentioned in a news article or something. I've done the mention script, but it splits the users name after it finds a space. When an user wants to mention somebody they will start their name with a @ symbol.

So my script stops after it finds a space. That means if I wanted to mention an username such as @This is. It would only pick up This.

Could anyone tell me how I can pick up usernames with spaces in? Here is my script.

<?php

$string = "I'm wanting to speak to the user @This is please.";
$explosion = explode("@", $string);
$count = count($explosion);

for($i = 0; $i < $count; $i++){
$explosion2 = explode(" ", $explosion[$i]);
$explosion2 = $explosion2[0];

$string = str_replace("@{$explosion2}", "{$explosion2} yeah", $string);
}

echo $string;
?>


Thank you.

Jon Jon
Answer

There's no way to figure out if a username is just one word or multiple words from your example because the username has the exact same formatting as the rest of the string. There are a few ways you can fix this.

You explode on @ then read up until you reach some indicator of the end of the username. So strings would then need to be altered to have special indicators at the beginning AND END of usernames:

$string = "I'm wanting to speak to the user @This is@ please.";

This would be very convenient for you because you would only have to call explode once since the whole username would be in the array's second element.

Comments