I want to get all the usernames from a post and send them notification.
The post may look like this.
Congratulations
@user1
@user2
@user3
You have won!
I want to select all words from the above string that contains @
symbol and store them as elements of an array so I can use them individually to send a notification to them.
I am using the following code but it gives only on 1 user. How do I get the rest of them?
<?php
$post = "Congratulations
@user1
@user2
@user2
You have won!";
if (strpos($post, "@")) {
$fetch = explode("@", $post);
$show = explode("
", $fetch[1]);
$users = count($show);
foreach ($show as $value) {
echo "$value <br>";
}
echo "<br>Total $users users.";
}
?>
UPDATE:
I tried to get the users as suggested by @Pharaoh
<?php
$post = "Congratulations
@user1
@user2
@user2
You have won!";
if (strpos($post, "@")) {
$matches = [];
preg_match_all('/@(\w+)/', $post, $matches);
$users = count($matches);
$matches = array_values($matches);
foreach ($matches as $value) {
echo "$value <br>";
}
echo "<br>Total $users users.";
}
?>
It gives two arrays as output as below.
Array
Array
Total 2 users.
What am I doing wrong?
You can iterate each row and check if the row starts with a @
or not:
$post = "Congratulations
@user1
@user2
@user2
You have won!";
// Explode the rows on line break
$rows = explode("
", $post);
// Create a new empty array where we can store all the users
$users = [];
foreach ($rows as $row) {
// Check if the current row starts with a @
if (strpos($row, '@') === 0) {
// Trim away the @ from the start and push the username to the users array
$users[] = ltrim($row, '@');
}
}
var_dump($users);
I would do this with regular expressions:
$matches = [];
preg_match_all('/@(\w+)/', $post, $matches);
var_dump($matches);
That way, your usernames don't need to be at the start of a line:
This is a sentence with @user1 in the middle.
You can see it in action here: https://eval.in/847703
(In case of an error, reload. Eval.in currently seems to have problems)
one way for get sub strings use regex (PHP Regular Expressions). in this case :
$post = "Congratulations
@user1
@user2
@user2
You have won!";
$usernames=preg_grep("/^@[\w\d]+/", explode("
", $post));
and you can try in here