从另一个字符串中搜索字符串并将这些字符串添加到array[closed]
题
我的弦是:
$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',
);
任何能帮我的人。.请.非常感谢!
解决方案
你可以使用这个正则表达式 '/#(\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
)
其他提示
在这儿:
$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);
使用正则表达式whith 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);
不隶属于 StackOverflow