$query = "Hello #world What's #up"
$newquery = "world, up"
所以基本上我wan't刪除的話不是以#PHP - 如何獲得,從第單詞和從字符串中刪除其他
$query = "Hello #world What's #up"
$newquery = "world, up"
所以基本上我wan't刪除的話不是以#PHP - 如何獲得,從第單詞和從字符串中刪除其他
你可能分裂的空間和循環遍歷字符串開始得到的數組,檢查第一個字符是否是#
。喜歡的東西:
$bits = explode(' ', $query);
$newquery = array();
foreach($bits as $bit){
if(strlen($bit) > 0 && $bit[0] === '#') $newquery[] = $bit;
}
$newquery = implode(', ', $newquery);
您還可以使用正則表達式,如(?:\#([^\s]+))
獲得匹配的詞。
編輯:作爲Scopey指出的,我的初始正則表達式可以改進(下面改變)和應該使用$matches[1]
,作爲返回的數組是多維的。請參閱:http://php.net/manual/en/function.preg-match-all.php
這可能看起來是這樣的:在空間
preg_match_all('/#([^#\s]+)/', $query, $matches);
$newquery = implode(', ', $matches[1]);
對於'preg_match_all'回答爲+1,但正則表達式可以改進爲'/#([^#\ s] +)/',因爲這會考慮到所有匹配項,例如'#hello#test'彼此。你也必須像這樣implode匹配:'implode(',',$ matches [1]);'。你也不能使用'g'作爲正則表達式修飾符。 – Scopey 2014-10-01 22:52:38
我認爲'g'修飾符只適用於Javascript。但是,我可能是錯的。 – 2014-10-01 22:55:13
良好的漁獲@Scopey,我編輯了我的答案 – 2014-10-01 22:56:57
分割,然後遍歷每個元素,看看它是否以「#」開頭。 – Dave 2014-10-01 22:43:44