如何在PHP中从包含特定字符或符号的字符串中选择单词?
我想从帖子中获取所有用户名并发送通知 帖子可能是这样的如何在PHP中从包含特定字符或符号的字符串中选择单词?,php,Php,我想从帖子中获取所有用户名并发送通知 帖子可能是这样的 Congratulations @user1 @user2 @user3 You have won! 我想从上面包含@符号的字符串中选择所有单词,并将它们存储为数组元素,以便我可以单独使用它们向它们发送通知 我使用下面的代码,但它只提供了一个用户。我怎么才能得到剩下的呢 <?php $post = "Congratulations @user1 @user2 @user2 You have won!"; if (strpo
Congratulations
@user1
@user2
@user3
You have won!
我想从上面包含@
符号的字符串中选择所有单词,并将它们存储为数组元素,以便我可以单独使用它们向它们发送通知
我使用下面的代码,但它只提供了一个用户。我怎么才能得到剩下的呢
<?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.";
}
?>
我做错了什么?您可以迭代每一行,并检查该行是否以
@
开头:
$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);
您可以迭代每一行并检查该行是否以
@
开头:
$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);
我将使用正则表达式执行此操作:
$matches = [];
preg_match_all('/@(\w+)/', $post, $matches);
var_dump($matches);
这样,您的用户名就不必位于行首:
This is a sentence with @user1 in the middle.
您可以在此处看到它的作用:(如果出现错误,reload.Eval.In当前似乎有问题)我将使用正则表达式执行此操作:
$matches = [];
preg_match_all('/@(\w+)/', $post, $matches);
var_dump($matches);
这样,您的用户名就不必位于行首:
This is a sentence with @user1 in the middle.
您可以在此处看到它的作用:(如果出现错误,reload.Eval.In当前似乎有问题)获取子字符串的一种方法是使用正则表达式(PHP正则表达式)。 在这种情况下:
$post = "Congratulations
@user1
@user2
@user2
You have won!";
$usernames=preg_grep("/^@[\w\d]+/", explode("\n", $post));
您可以尝试使用regex(PHP正则表达式)以一种方式获取子字符串。 在这种情况下:
$post = "Congratulations
@user1
@user2
@user2
You have won!";
$usernames=preg_grep("/^@[\w\d]+/", explode("\n", $post));
你可以试一试