识别多个以@开头的字符串


Recognize multiple strings starting with @

我希望我的php能够识别以@符号开头的字符串中的多个字符串。然后将其转换为变量

//whole string
$string = "hello my name is @mo and their names are @tim and @tia."
//while loop now?

@mo@tim@tia应转换为变量,如:

$user1 = "mo";
$user2 = "tim";
$user3 = "tia";

有没有一个php命令可以用来将它们全部收集到一个数组中?

正则表达式是一种非常灵活的模式识别工具:

<?php
$subject = "hello my name is @mo and their names are @tim and @tia.";
$pattern = '/@('w+)/';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);

输出为:

array(2) {
  [0] =>
  array(3) {
    [0] =>
    string(3) "@mo"
    [1] =>
    string(4) "@tim"
    [2] =>
    string(4) "@tia"
  }
  [1] =>
  array(3) {
    [0] =>
    string(2) "mo"
    [1] =>
    string(3) "tim"
    [2] =>
    string(3) "tia"
  }
}

所以$token[1]是您感兴趣的数组。

也许,您使用正则表达式来匹配所有以"@"开头的字符串,并将其放入数组中?

preg_match_all("|'@(.*)[ .,]|U",
    "hello my name is @mo and their names are @tim and @tia.",
    $out, PREG_PATTERN_ORDER);

out现在具有匹配的字符串。。

附言:我不是PHP开发人员。刚刚在网上试用了一些东西编译器。!