我的评论中包含提及的userId,如下所示:
$subject = "@1 likes @12 and @123";
现在,我想用数组中的真实名称替换这些id:
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];
我陷入了亨利用户可以像这样替换所有包含@ 1的id的情况:
$subjectReplaced = "@Henry likes @Henry2 and @Henry23"
// What I want is:
$subjectReplaced = "@Henry likes @Tony and @Pizza";
有人帮我吗?
完整代码在这里:
<?php
$subject = "@1 likes @12 and @123";
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];
foreach ($users as $id => $user) {
$subject = str_replace('@' . $id, '@' . $user, $subject);
}
echo $subject;
答案 0 :(得分:1)
您可以根据空格爆炸subject
,并对收到的每个令牌进行preg_match
。如果令牌与您的@some_text
格式匹配,我们将在下面的subject_data
数组中进行替换。最后,我们只需执行implode()即可获取替换后的字符串。
<?php
$users = ['1' => "Henry", '12' => "Tony", '123' => "Pizza"];
$subject = "@1 likes @12 and @123";
$subject_data = explode(" ",$subject);
foreach($subject_data as $key => $each_data){
if(preg_match('/@.+/',$each_data) === 1){
$subject_data[$key] = "@" . $users[substr($each_data,1)];
}
}
echo implode(" ",$subject_data);
请注意,这也可以解决重叠问题,也可以说前缀字符串问题,例如@1
和@12
。我不使用str_replace()
的原因之一。
答案 1 :(得分:1)
另一种使用preg_split
来中断字符串的方法,然后循环遍历中断字符串的各个部分,并用相关的用户ID替换ID,最后使用implode
来连接字符串的各个部分。 / p>
$subject = "@1 likes @12 and @123";
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];
$parts = preg_split("/(\@\d*)/", $subject, 0, PREG_SPLIT_DELIM_CAPTURE);
foreach ($parts as &$part) {
if (strpos($part, '@') !== 0) {
continue;
}
$part = $users[substr($part, 1, strlen($part) - 1)] ?? '';
}
$result = implode($parts);
echo $result;
结果: 亨利喜欢托尼和比萨饼
测试here
答案 2 :(得分:0)
您可以将array_walk
与str_replace
一起使用
$subject = "@1 likes @12 and @123";
$patterns = ['1' => 'Henry','12' => 'Tony' ,'123' => 'Pizza'];
$previousKey ='';
array_walk($patterns, function($v, $k) use (&$subject, &$previousKey, $patterns){
if(!empty($previousKey))
$subject = str_replace(str_replace($previousKey, $patterns[$previousKey], $k), $v, $subject);
else
$subject = str_replace($k, $v, $subject);
$previousKey = $k;
$previousKey = $k;
});
echo $subject;
答案 3 :(得分:0)
您可以只使用strtr
进行替换。 strtr
对这项工作很有用,因为它先替换了较长的字符串,然后不再查看它们,从而避免了可能出现的双重替换问题。
$subject = "@1 likes @12 and @123";
$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];
echo strtr($subject, $users);
输出:
@Henry likes @Tony and @Pizza