9阅网

您现在的位置是:首页 > 知识 > 正文

知识

php - php str_replace() 搜索中的重复词语

admin2022-11-07知识20

试图搜索并替换一些内容,使用 str_replace(). 它的工作正常,如果 $find 是唯一的,但一旦如果 $find 有重复的字,整个事情就乱了。

如:The style1 将适用于两个 $find[0] && $find[1] 既然都 Lorem Ipsum,同样的道理 dummy.

如何处理这种情况?

$find = Array(
    [0] => Lorem Ipsum 
    [1] => Lorem Ipsum 
    [2] => typesetting 
    [3] => dummy 
    [4] => dummy 
);

$replace = Array(
    [0] => style1
    [1] => style2
    [2] => style3
    [3] => style4
    [4] => style5
);

$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
           Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
           when an unknown printer took a galley of type and scrambled it to make a type specimen book.";

$result = str_replace($find,$replace,$string);
echo $result;


【回答】:

你可以使用一个实现 str_replace_first 如同 这个问题 并在你的 $find$replace 数组中的每一个值都替换掉一个出现在 $find 只有数组。

function str_replace_first($search, $replace, $subject) {
    if (($pos = strpos($subject, $search)) !== false) {
        return substr_replace($subject, $replace, $pos, strlen($search));
    }
    return $subject;
}

$result = $string;
foreach ($find as $key => $search) {
    $result = str_replace_first($search, $replace[$key], $result);
}
echo $result;

输出。

style1 is simply style4 text of the printing and style3 industry. 
style2 has been the industry's standard style5 text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type specimen book.

3v4l.org上的演示