php - str_replace 替换错误值的问题
问题描述
我正在尝试用相关标题替换数字列表(ID),问题是当标题有数字时也会被替换,例如:
$idlist = "1, 2, 3";
$a = array(17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
$b = array('Star Trek 7', 'Superman 8', 'Toy Story 2', 'Terminator 3', 'Other', 'Superman 4', 'Star Trek 3', 'Superman 3', 'Mad Max 3', 'Mad Max 2', 'Superman 3', 'Superman 2', 'Christmas Vacation 3', 'Star Trek 2', 'Terminator 2', 'Toy Story 3', 'Mission Impossible 2');
echo str_replace($a, $b, $idlist);
错误的当前结果:
Mission Impossible 2, Toy Story 3, Terminator Toy Story 3
应该:
Mission Impossible 2, Toy Story 3, Terminator 2
有什么更好的方法来做到这一点?
解决方案
strtr
改为尝试str_replace
:
$idlist = "1, 2, 3";
$a = array(17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
$b = array('Star Trek 7', 'Superman 8', 'Toy Story 2', 'Terminator 3', 'Other', 'Superman 4', 'Star Trek 3', 'Superman 3', 'Mad Max 3', 'Mad Max 2', 'Superman 3', 'Superman 2', 'Christmas Vacation 3', 'Star Trek 2', 'Terminator 2', 'Toy Story 3', 'Mission Impossible 2');
$pairs = array_combine($a, $b);
echo strtr($idlist, $pairs);
结果:
Mission Impossible 2, Toy Story 3, Terminator 2
推荐阅读
- python - 我可以在 TensorFlow 自定义层中添加 if...else 吗?
- c - memmove 是否为其临时数组使用动态内存
- c# - 如何在 C# 的递归函数或其他可用选项中使用 db.savechange() 函数提高实体框架中数据保存的性能?
- roblox - 需要围绕 x 轴旋转人形模型
- angular - Angular AOT 编译正在删除 openlayers 所需的代码
- php - 如何在koolreport的koolreport_assets目录下禁用动态目录创建?
- security - 如何在 https 响应中隐藏 cookie 路径
- c# - npoi c#列号差异
- linux - sed.exe -e 表达式 #1,未知命令
- git-tfs - 我可以使用 Git tfs 重新迁移到现有的 git repo