所以我正在做一个项目,我正在将@misterFoo
转换为@[:1234]
(他的用户ID)。
这一切都有效,我很高兴,但我也想恢复这一点。
我已经找到了捕获@[:1234]
的正则表达式,但是当出现第二次出现时,就像这个字符串中一样:
"Joo @[:1234] my buddy @[:5678] want's his money back"
我只能通过正则表达式获得@[:1234]
/(@'[:[0-9]])/
我可能像+
一样缺少多个单词或数字边界,或者'b
有人可以解释我需要什么?
有人在此正则表达式中的评论中给出了正确的答案:https://regex101.com/r/lL9lB4/1
现在我面临着如何让1234
摆脱@[:1234]
的麻烦
只需将与数字匹配的模式放在捕获组中即可。
@'[:([0-9]+)']
从组索引 1 中获取所需的字符串。
演示
或
@'[:'K[0-9]+(?='])
演示
$re = "/@''[:''K[0-9]+(?=''])/";
$str = "Joo @[:1234] my buddy @[:5678] want's his money back";
preg_match_all($re, $str, $matches);
修复了这是我为解决它而制作的函数:
这是将字符串中的用户名转换为数据库的@[:id]的函数
public function replaceUsernames($text){
$pattern = '/@'w+'b/';
preg_match_all($pattern, $text, $matches);
$sql = $this->db->prepare("
SELECT `id`
FROM `users` u
WHERE `username` = :username LIMIT 1
");
foreach($matches[0] as $value){
$value = str_replace('@','',$value);
$sql->execute(
array(
'username' => $value
)
);
if($sql->rowCount() > 0){
$user = $sql->fetchObject();
$text = str_replace($value,'[:'.$user->id.']',$text);
}
}
return($text);
}
这是从我的数据库中获取数据的反向函数:
public function replaceUserids($text){
$pattern = '/(@'[:[0-9]+'])/';
preg_match_all($pattern, $text, $matches);
$sql = $this->db->prepare("
SELECT `username`
FROM `users` u
WHERE `id` = :id LIMIT 1
");
foreach($matches[0] as $value){
preg_match('/[0-9]/',$value, $match);
$id = $match[0];
$sql->execute(
array(
'id' => $id
)
);
if($sql->rowCount() > 0){
$user = $sql->fetchObject();
$text = str_replace($value, '@'.$user->username,$text);
}
}
return($text);
}
你试过使用 preg_match_all 吗?