0

我想用 php 做一些简单的替换。

对于第一次出现的 "xampp" ,将其替换为 "xp"。

对于“xampp”的第二次/最后一次出现,将其替换为“rrrr”

    $test = "http://localhost/xampp/splash/xampp/.php";

echo $test."<br>";
$count = 0;
$test = str_replace ("xampp","xp",$test,$count);

echo $test."<br>";

$count = 1;
$test = str_replace ("xampp","rrrr",$test,$count);
echo $test;

查看文档后,我发现 $count 是只返回字符串匹配的地方。它不会用指定的特定匹配项替换字符串。那么有什么方法可以完成任务吗?

4

1 回答 1

1

您可以使用 来执行此操作preg_replace_callback,但strpos如果替换不一定是顺序的,则应该更有效。

function replaceOccurrence($subject, $find, $replace, $index) {
    $index = 0;

    for($i = 0; $i <= $index; $i++) {
        $index = strpos($subject, $find, $index);

        if($index === false) {
            return $subject;
        }
    }

    return substr($subject, 0, $index) . $replace . substr($subject, $index + strlen($find));
}

这是一个演示。

于 2012-12-09T16:42:48.063 回答