【发布时间】:2019-12-31 05:19:26
【问题描述】:
我的函数从文本中提取@users、#hashtags 链接和表情符号
function convert_text($str) {
$regex = "/[@#](\w+)/";
//type and links
$hrefs = [
'#' => 'hashtag.php?hashtag',
'@' => 'user.php?user'
];
$result = preg_replace_callback($regex, function($matches) use ($hrefs) {
return sprintf(
'<a href="%s=%s">%s</a>',
$hrefs[$matches[0][0]],
$matches[1],
$matches[0]
);
}, $str);
//$result = preg_replace("/U\+([A-F0-9]{5})/", '\u{${1}}', $result);
$result = preg_replace('/U\+([A-F0-9]{5})/', '<span style="font-size:30px;">&#x\\1;</span>', $result);
return ($result);
}
我想创建另一个函数来提取仅@users和
插入notify 表foreach @user 在文本中找到
查询类似于:
$query = "INSERT INTO notify ('from_user', 'notification') VALUES ('$users_found)
也许
foreach($user_found as $user => $u){
//execute query
}
例如:text here @user1 test @user2
提取@user1, @user2
并使用foreach user found 插入数据库
解决这个问题的最佳方法是什么?
PDO 示例
function update_notifications($str) {
global $conexao_pdo;
if (preg_match_all("/@(\w+)/", $str, $matches)) {
$query = "INSERT INTO notification (from_who, type, to_user, time, notification_seen) VALUES (:from_who, :type, :to_user, :time, :notification_seen)";
$notifications = array();
foreach ($matches[1] as $user) {
//$notifications[] = "('$user', '$user found in \'$str\'')";
$notifications = "('$user')";
}
$query .= implode(',', $notifications);
}
// execute query
//echo $query;
$notification_seen = "no";
$l = "like";
$time = date('d-m-Y G:i:s');
$notify = $conexao_pdo->prepare($query);
$notify->bindParam(':from_who', $user_logged);
$notify->bindParam(':type', $l);
$notify->bindParam(':to_user', $notifications);
$notify->bindParam(':time', $time);
$notify->bindParam(':notification_seen', $notification_seen);
$notify->execute();
}
update_notifications('text here @user1 test @otaviobarreto');
【问题讨论】:
-
你能展示一些示例输入数据和预期输出吗?
-
示例:
text here @user1 test @user2提取@user1, @user2并在找到foreach user的情况下插入数据库 -
@OtávioBarreto 刚刚尝试了一个简单的解决方案来获得您想要的结果
标签: php regex function for-loop foreach