【问题标题】:str_replace for multiple items then store results in new variablestr_replace 用于多个项目,然后将结果存储在新变量中
【发布时间】:2016-02-22 01:50:07
【问题描述】:

我有一个这样的字符串:

 $content = 'Hi @steve, have you seen what @dave wrote?';

我基本上只想找到直接跟在 @ 符号后面的单词(如 twitter 提及),然后循环遍历每个结果,与它们一起执行任务。

我知道如何从整个字符串中去掉 @ 字符:

$strip_at = str_replace( '@', '', $content );

这将导致 $strip_at 成为:

Hi steve, have you seen what dave wrote?

但是我将如何使用 str_replace 来定位每个“提及”,删除仅留下单词(在本例中为名称)的 @ 符号,然后将每个“提及”的结果存储在一个数组中到一个新变量中?

想要的结果:

$mentions = array('steve','dave');

然后我可以遍历 $mentions 并对结果进行处理,例如:

foreach ($mentions as $mention) {
   echo 'This persons name is '.$mention.'<br />';
}

【问题讨论】:

    标签: php arrays variables str-replace


    【解决方案1】:

    您可以通过正则表达式完成此操作:

    preg_match_all('/(?<=@)(\w){1,15}/', $content, $results);
    

    这会将这个数组存储在变量$results中:

    [
         [
           "steve",
           "dave",
         ],
       ]
    

    你可以通过循环$results[0]来枚举匹配:

    foreach($results[0] as $name) {
      echo $name . '<br>';
    }
    

    打印:

    steve
    dave
    

    如果您对 /(?&lt;=@)(\w){1,15}/ 的含义感到好奇:

    (?&lt;=@) - “lookbehind” - 这意味着 我们需要一个 @ 来放在我们真正感兴趣的匹配之前

    (\w){1,15} 表示匹配最大长度为 15 的单词(推特名称的最大大小)

    所以我们一起匹配@符号后面的推特用户名。

    【讨论】:

    • 那么 $results 将是我然后循环遍历的变量吗? $results 为 $result
    • @Grant 你会遍历$results[1] 喜欢:foreach($results[1] as $name) echo $name;
    • 好吧,听起来很完美!有没有办法不存储原始的 steve, dave 对象(带有 @ 符号),因为它们永远不会被需要?所以基本上我可以使用 $results[0] 而不是 $results[1]
    • @Grant 是的,看我的编辑帖子,你可以使用preg_match_all('/(?&lt;=@)(\w){1,15}/', $content, $results);
    • 非常感谢,最后$results[10] 你的意思是$results[0] 对吗?只是检查?
    猜你喜欢
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多