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.
$data = "123_String"; $whatIWant = substr($data, strpos($data, "_") + 1); echo $whatIWant; Php Get String After Character.
Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
Using str_contains. The str_contains is a new function that was introduced in PHP 8. This method is used to check if a PHP string contains a substring. The function checks the string and returns a boolean true in case it exists and false otherwise.
The first word of a sentence can be obtained with the help of various inbuilt functions like strtok(), strstr(), explode() and some other methods like using regular expressions.
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
}
}
?>
/
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 _
.(?<!\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.\w+
means, "One or more word characters." The +
is known as a quantifier.\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.
Looks like a job for preg_replace_callback():
$string = preg_replace_callback('/@([a-z0-9_]+)/', function ($matches) {
if ($user = get_user_by_username(substr($matches[0], 1)))
return '<a href="user.php?user_id='.$user['user_id'].'">'.$user['name'].'</a>';
else
return $matches[0];
}, $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With