I have a string that has hash tags in it and I'm trying to pull the tags out I think i'm pretty close but getting a multi-dimensional array with the same results
我有一个字符串里面有散列标签我试着把标签拉出来我想我已经很接近了但是得到了一个多维数组,结果是一样的
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches);
print_r($matches);
which yields
的收益率
Array (
[0] => Array (
[0] => "#a"
[1] => "#some"
[2] => "#hash"
)
[1] => Array (
[0] => "#a"
[1] => "#some"
[2] => "#hash"
)
)
I just want one array with each word beginning with a hash tag.
我只想要一个数组,每个单词都以哈希标签开头。
4 个解决方案
#1
14
this can be done by the /(?<!\w)#\w+/
regx it will work
这可以通过/(? ! ? !)#\w+/ regx来实现
#2
3
That's what preg_match_all
does. You always get a multidimensional array. [0]
is the complete match and [1]
the first capture groups result list.
这是什么preg_match_all。你总是得到一个多维数组。[0]是完全匹配,[1]是第一个捕获组结果列表。
Just access $matches[1]
for the desired strings. (Your dump with the depicted extraneous Array ( [0] => Array ( [0]
was incorrect. You get one subarray level.)
只需访问与所需字符串匹配的$[1]。(您的转储使用所描述的无关数组([0]=>数组)([0]不正确)。你得到一个子数组级别)
#3
2
I think this function will help you:
我认为这个函数可以帮助你:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
#4
0
Try:
试一试:
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?<!\w)#\S+/', $string, $matches);
print_r($matches[0]);
echo("<br><br>");
// Output: Array ( [0] => #a [1] => #some [2] => #hash )
#1
14
this can be done by the /(?<!\w)#\w+/
regx it will work
这可以通过/(? ! ? !)#\w+/ regx来实现
#2
3
That's what preg_match_all
does. You always get a multidimensional array. [0]
is the complete match and [1]
the first capture groups result list.
这是什么preg_match_all。你总是得到一个多维数组。[0]是完全匹配,[1]是第一个捕获组结果列表。
Just access $matches[1]
for the desired strings. (Your dump with the depicted extraneous Array ( [0] => Array ( [0]
was incorrect. You get one subarray level.)
只需访问与所需字符串匹配的$[1]。(您的转储使用所描述的无关数组([0]=>数组)([0]不正确)。你得到一个子数组级别)
#3
2
I think this function will help you:
我认为这个函数可以帮助你:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
#4
0
Try:
试一试:
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?<!\w)#\S+/', $string, $matches);
print_r($matches[0]);
echo("<br><br>");
// Output: Array ( [0] => #a [1] => #some [2] => #hash )