2014-01-19 46 views
1

我想把一个带有hashtags的字符串分成单个hashtag。PHP没有空格的hashtags字符串没有被分成hashtags

我使用这段代码:如果用户插入带有空格的主题标签

preg_match_all('/#([^\s]+)/', $str, $matches); 

#test #test #test #example 

这一个工作正常。但是如果他们直接跟随对方呢?

#test#test#test#example 

回答

1

试试这个:

preg_match_all('/#(\w+)/', $str, $matches); 

例子:

<?php 
$str = '#test #test2 #123 qwe asd #rere#dada'; 
preg_match_all('/#(\w+)/', $str, $matches); 
var_export($matches); 

输出:

array (
    0 => 
    array (
    0 => '#test', 
    1 => '#test2', 
    2 => '#123', 
    3 => '#rere', 
    4 => '#dada', 
), 
    1 => 
    array (
    0 => 'test', 
    1 => 'test2', 
    2 => '123', 
    3 => 'rere', 
    4 => 'dada', 
), 
) 

我认为学习RegEx将帮助您解决这些问题。

1

你可以做

$tags = explode('#', $string); 
foreach($tags as $key => $tag) 
    $tags[$key] = '#' . $tag; 
相关问题