-1

在 php 中,如何扫描文本(以用户提交的消息的形式)查找多个字符串(以其他用户名的形式)?

例如,在用户提交消息下方,我想要一种“查找”字符串“user-one”和“user-two”并将这些字符串发送到数组中的方法。

你好,这是一条测试消息,你能看到它@user-one,@user-two 吗?

4

4 回答 4

2

你可以试试

$message = "Hello this is a test message, can you see it @user-one, @user-two?" ;
preg_match_all("/\@[a-z\-]+/", $message,$match);
var_dump($match[0]);

输出

array (size=2)
  0 => string '@user-one' (length=9)
  1 => string '@user-two' (length=9)
于 2013-01-02T21:51:09.487 回答
0
preg_match_all('|\@(.*) |' , $userText , $match);

print_r($match[1])

$match[1]将包含所有用户名。$userText是用户输入的文本。如果$match[0]您希望用户名带有@.

于 2013-01-02T21:50:12.293 回答
0

您可以使用 strrpos 检索位置并使用 substr + strlen 获取文本。例子:

...
$mystring = "Hello this is a test message, can you see it @user-one, @user-two?";
$pos = strrpos($mystring, "@user-one");
if ($pos > 0) {
    $str = substr($mystring, $pos, strlen("@user-one"));
}
...

对不起,如果我没有正确理解这个问题。

于 2013-01-02T22:00:46.010 回答
0

没有凌乱的模式匹配这个!

function stringToUserArray($str) { 
$remove = array(".",",","!","?");
$str = str_replace($remove, " ", $str);
$array = explode(" ", $str);
foreach($array as $string) { 
    if($string[0] == "@") { 
        $users[] = $string;
    }
}

return $users;
}
于 2013-01-02T22:11:50.563 回答