2013-03-05 45 views
1

我試圖從字符串中提取使用preg_match_all的hashtags,並使用foreach循環執行MySQL數組值插入操作。但顯然它還沒有工作,這就是爲什麼我在這裏。執行mysql查詢循環返回preg_match_all的數組

我的代碼是這樣的:

<?php 

$text = "this has a #hashtag a #badhash-tag and a #goodhash_tag"; 
preg_match_all('/#[^\s]*/i', $text, $matches); 

foreach($matches as $value){ 
    echo $value.'<br>'; // right now, im just trying to see if i can get individual array values and then will have to perform sql query here 
} 

?> 

我知道這是一個有點天真,但我無法弄清楚。請指導。

+0

丹尼貝克特,S由於不好的縮進和語言。我英語不錯,只是匆忙:)感謝編輯。 – coder101 2013-03-05 06:45:30

回答

1

使用該for循環中,$matches是多維數組

foreach($matches[0] as $value){ 
     echo $value.'<br>'; // right now, im just trying to see if i can get individual array values and then will have to perform sql query here 
} 

工作示例http://codepad.viper-7.com/iEGvgh

輸出:

#hashtag 
#badhash-tag 
#goodhash_tag 
+1

謝謝你。完美工作.. – coder101 2013-03-05 06:41:44

0

嘗試這種情況:

$text = "this has a #hashtag a #badhash-tag and a #goodhash_tag"; 
preg_match_all('/#(?P<hash>\w+)/', $text, $matches); 

foreach($matches['hash'] as $val){ 
    echo $val; 
    echo "<br>"; 
}