我的提及系统需要添加内容。我创建了以下代码,用于使用php和mysql保存提到的用户。
文本为:
$text = 'Hi @john ! Need help @stack .';
保存查询
$mention_regex = '/@([A-Za-z0-9_]+)/i';
preg_match_all($mention_regex, $text, $matches);
foreach ($matches[1] as $match) {
$match = mysqli_real_escape_string($db, $match);
}
$mentionTime = time();
$mention_sql = mysqli_query($db,"
INSERT INTO mentions (m_uid_fk,
m_status,
m_time )
SELECT user_id, '$uid','$mentionTime'
FROM users
WHERE user_name IN ('" .implode("','", $matches[1]). "')")
or die(mysqli_error($db));
我的问题是:如果文本中有一个指定的用户名,例如@john
,则不要为此用户名保存提及表。
反正我的查询可以做到这一点吗?
答案 0 :(得分:0)
您可以使用strpos检查字符串中的某些文本:
$search = '@john';
$string = 'Hi @john ! Need help @stack .';
if (!strpos($string, $search)) {
# run save code
}
替代答案
使用array_filter-
$users = ['@john', '@trey', '@azzo'];
$data = array_filter($users, function($el)
{
return ($el !== '@john');
});
echo '<pre>'. print_r($data, 1) .'</pre>';
通过array_filter
,您可以使用一个根据条件检查元素的函数来指定返回值。然后只需foreach
个$data
数组,并仅为此运行代码即可。
例如
foreach ($data as $item)
{
# run save code
}