执行mysql查询循环遍历preg_match_all返回的数组

时间:2013-03-05 06:35:13

标签: php mysql preg-match-all

我正在尝试使用preg_match_all从字符串中提取主题标签,并使用foreach循环对数组值执行MySQL插入。但显然它还没有工作,这就是我在这里的原因。

我的代码就像:

<?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
}

?>

我知道这有点天真,但我无法弄清楚。请指导。

2 个答案:

答案 0 :(得分: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 :(得分: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>";
 }