首页 > 解决方案 > 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

有什么更好的方法来做到这一点?

标签: php

解决方案


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

推荐阅读