我为我的网站设计了一个标签系统,其中以散列(#)函数开始的标签与不以散列(#)函数开始的标签不同。我试图从我的数据库中提取所有的哈希标签,并将它们加载到一个数组:
$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);
}
}
}
MySQL查询返回以下内容:
+------------------------+
| Keywords |
+------------------------+
| #test1, test |
| #test1, #test2, #test4 |
| #test3, #est5 |
| #test3 |
+------------------------+
我想要一个这样的数组:
Array(
[0] => #test1
[1] => #test2
[2] => #test4
[3] => #test3
[4] => #est5
)
我做错了什么?
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);
输出:Array
(
[0] => #test1
[1] => #test4
[2] => #test2
[3] => #est5
[4] => #test3
)
试试这个regexp: preg_match("/^'#'w+$/", $wrds, $matched);
正如@NullUserException所说,在RDBMS中放置序列化值是糟糕的设计,这样做只会使事情变得复杂。
对于你的问题,你可以试试另一种方式:
$result = array_filter(explode(',', $wrds), function($a){ return $a[0]==='#' } );