我尝试使用单词在数组中显示的次数来更新数据库。我发现strpos作为一个函数只能使用一次 - 但如果单词('示例')被使用了三次,我希望返回的值为3 - 而不是'真正的&#39 ;.
我目前的代码:
$count = mysql_real_escape_string($_POST['item_name']);
if (strpos($count,'example') !== false) {
mysql_query("UPDATE table SET value = value + 1 WHERE id = '1'");
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
}
我知道我以错误的方式解决这个问题,但是什么是正确的方法?谢谢!
答案 0 :(得分:0)
preg_match_all查找给定字符串中的所有模式匹配,如果找不到任何内容则返回false。
$matches = array(); // Not Used
$count = implode('_',$yourArrayHere, $matches); // Compresses array to one big string
$found = preg_match_all('/example/', $count); // Searches that string.
if($found !== false && $found > 0) {
mysql_query("UPDATE table SET value = value + ".(int)$found." WHERE id = '1'");
}
答案 1 :(得分:0)
如下:
$map = array();
for($array as $key)
{
if(isset($map[$key]))
{
$map[$key] = $map[$key] + 1;
}
else
{
$map[$key] = 1;
}
}
答案 2 :(得分:0)
preg_match_all()应该为您提供所需的答案。
$itemName = preg_quote(implode(' ', $_POST['item_name']));
$searchWord = 'example';
$numMatches = preg_match_all("/\b$searchWord\b/", $matches); //$matches is filled with the results
mysql_query("UPDATE table SET value = value + $numMatches WHERE id = '1'");
我不确定你为什么在你的例子中调用mysql_real_escape_string()。 $ itemName永远不会注入SQL,因此不需要使SQL安全。我用preg_quote()替换了转义调用,它会转义正则表达式特殊字符。