【问题标题】:search string from another string and add these string to array [closed]从另一个字符串中搜索字符串并将这些字符串添加到数组中[关闭]
【发布时间】:2014-04-11 08:52:03
【问题描述】:

我的字符串是:

$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";

我想从该字符串中获取#fox, #dog#lazy 以及包含# 的每个单词,并且我想将这些字符串添加到这样的数组中:

 $array = array(
       [0]=>'#fox',
       [1]=>'#dog',
       [2]=>'#lazy',
   );

任何可以帮助我的人.. 请。非常感谢!

【问题讨论】:

  • StackOverflow 为此? O tempora..

标签: php arrays regex function output


【解决方案1】:

你可以使用这个正则表达式'/#(\w+)/'

<?php
$str = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
preg_match_all('/#(\w+)/', $str, $matches);
array_walk($matches[1],function (&$v){ $v='#'.$v;});
print_r($matches[1]);

输出:

Array
(
    [0] => #fox
    [1] => #dog
    [2] => #lazy
)

【讨论】:

  • "还有每个包含#的单词"-不清楚OP是否想匹配foo#bar
  • 我明白了。太感谢了!你的代码真的很酷.. :)
【解决方案2】:

这里是:

$s = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
$r = array();
preg_match_all('/(?<!\w)#\w+/', $s,$r);
print_r($r);

【讨论】:

    【解决方案3】:

    使用带有preg_match_all 的正则表达式,您会得到一个数组,其中所有以# 开头的单词都包含在字符串中。

    $str  = "a quick brown fox over the lazy dog... #fox #dog. hello everybody #lazy";
    $pattern = '/(?<!\w)#\w+/';
    preg_match_all($pattern, $str , $matches);
    print_r($matches);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 2020-04-13
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多