我希望从帖子中获取所有用户名并向其发送通知。
帖子可能看起来像这样。
Congratulations
@user1
@user2
@user3
You have won!
我想从上面包含@
符号的字符串中选择所有单词并将它们存储为数组元素,这样我就可以单独使用它们向它们发送通知。
我使用以下代码,但它仅提供给1个用户。我如何得到其余的?
<?php
$post = "Congratulations
@user1
@user2
@user2
You have won!";
if (strpos($post, "@")) {
$fetch = explode("@", $post);
$show = explode("\r\n", $fetch[1]);
$users = count($show);
foreach ($show as $value) {
echo "$value <br>";
}
echo "<br>Total $users users.";
}
?>
更新
我试图按照@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.";
}
?>
它提供两个数组作为输出,如下所示。
Array
Array
Total 2 users.
我做错了什么?
答案 0 :(得分:3)
我会用正则表达式做到这一点:
$matches = [];
preg_match_all('/@(\w+)/', $post, $matches);
var_dump($matches);
这样,您的用户名不需要在一行的开头:
This is a sentence with @user1 in the middle.
你可以在这里看到它:https://eval.in/847703
(如果出现错误,请重新加载.Eval.in目前似乎有问题)
答案 1 :(得分:1)
您可以迭代每一行并检查该行是否以@
开头:
$post = "Congratulations
@user1
@user2
@user2
You have won!";
// Explode the rows on line break
$rows = explode("\n", $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);
答案 2 :(得分:0)
获取子字符串的一种方法是使用正则表达式(PHP正则表达式)。 在这种情况下:
$post = "Congratulations
@user1
@user2
@user2
You have won!";
$usernames=preg_grep("/^@[\w\d]+/", explode("\n", $post));
您可以尝试here