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().
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;
结果: 亨利喜欢托尼和比萨
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;
- 3 回答
- 0 关注
- 129 浏览
添加回答
举报