2014-01-19 45 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; 
相關問題