为了账号安全,请及时绑定邮箱和手机立即绑定

在注释中按名称替换 id 而不替换错误的大小写

在注释中按名称替换 id 而不替换错误的大小写

PHP
互换的青春 2021-07-05 13:11:56
我有一条评论包含提到的 userId,如下所示:$subject = "@1 likes @12 and @123";现在我想用数组中的真实姓名替换这些 id:$users = [1 => "Henry", 12 => "Tony", 123 => "Pizza"];我陷入了 Henry 用户可以像这样替换所有包含 @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;
查看完整描述

3 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

您可以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().


查看完整回答
反对 回复 2021-07-09
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

另一种方法是使用preg_split来断开字符串,然后遍历断开的字符串的各个部分并用关联的用户 ID 替换 id,最后使用implode来连接字符串部分。


$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;

结果: 亨利喜欢托尼和比萨


查看完整回答
反对 回复 2021-07-09
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

你可以用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;


查看完整回答
反对 回复 2021-07-09
  • 3 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信