Check the word after a '@' character in PHP
character, php
Solution
This is where regular expressions come in.
<?php
$string = "I loved the article, @SantaClaus! And I agree, @Jesus!";
if (preg_match_all('/(?<!\w)@(\w+)/', $string, $matches))
{
$users = $matches[1];
// $users should now contain array: ['SantaClaus', 'Jesus']
foreach ($users as $user)
{
// check $user in database
}
}
?>
- The `/` at beginning and end are delimiters (don't worry about these for now).
- `\w` stands for a word character, which includes `a-z`, `A-Z`, `0-9`, and `_`.
- The `(?<!\w)@` is a bit advanced, but it's called a negative lookbehind assertion, and means, "An `@` that does not follow a word character." This is so you don't include things like email addresses.
- The `\w+` means, "One or more word characters." The `+` is known as a quantifier.
- The parentheses around `\w+` capture the portion parenthesized, and appear in `$matches`.
regular-expressions.info seems to be a popular choice of tutorial, but there are plenty of others online.
Problem
I'm making a news and comment system at the moment, but I'm stuck at one part for a while now. I want users to be able to refer to other players on the twitter style like @username. The script will look something like this: (not real PHP, just imagination scripting ;3) ``` $string = "I loved the article, @SantaClaus, thanks for writing!"; if($string contains @){ $word = word after @; $check = is word in database? ... } ``` And that for all the @username's in the string, perhaps done with a while(). I'm stuck, please help.