开发者

PHP / MySQL preg_match words beginning with hash symbol

I've devised a tagging system for my Website where tags beginning with a hash (#) function differently to those without. I'm trying to extract all hash tags from my database and load them into an array:

$keywords = mysql_query("SELECT Keywords FROM Tags WHERE Keywords LIKE '#%'") or die("Query failed with error: ".mysql_error());
$stack = array();
while ($row = mysql_fetch_array($keywords))
{
    $wrds = $row['Keywords'];
    $val = preg_match("/\b\#\w+(?=,|\b)/", $wrds, $matched);
    while (!empty($matched))
    {
        $val = array_pop($matched);
        if (array_search($val, $stack) === FALSE)
        {
            array_push($stack, $val);
    }
    }
}

The MySQL query returns the following:

+------------------------+
| Keywords               |
+------------------------+
| #test1, test           |
| #test1, #test2, #test4 |
| #test3, #est5          |
| #test3                 |
+------------------------+

I want a开发者_如何学Cn array like the following:

Array(
  [0] => #test1
  [1] => #test2
  [2] => #test4
  [3] => #test3
  [4] => #est5
  )

What am I doing wrong?


use preg_match_all :

$arr = array('#test1, test','#test1, #test2, #test4','#test3, #est5','#test3');
$stack = array();
foreach($arr as $wrds) {
    $val = preg_match_all("/#\w+(?=,|$)/", $wrds, $matched);
    while (!empty($matched[0])) {
        $val = array_pop($matched[0]);
        if (array_search($val, $stack) === FALSE)
        {
            array_push($stack, $val);
        }
    }
}
print_r($stack);

output:

Array
(
    [0] => #test1
    [1] => #test4
    [2] => #test2
    [3] => #est5
    [4] => #test3
)


try this regexp: preg_match("/^\#\w+$/", $wrds, $matched);


As @NullUserException said, it is bad design fo putting serialized values in RDBMS, doing this just make things complicated.

And for your question, you can try another way:

$result = array_filter(explode(',', $wrds), function($a){ return $a[0]==='#' } );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜