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

时间:2016-04-17 12:49:07

标签: php

我希望我的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命令可以用来在阵列中收集它们?

2 个答案:

答案 0 :(得分:1)

也许,你使用正则表达式匹配所有那些以" @"开头的字符串;并把它放在一个数组?

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

out现在有匹配的字符串..

  

PS:我不是PHP开发人员。刚尝试在线使用的东西   编译器。!

答案 1 :(得分:1)

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

<?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]是您感兴趣的数组。