【问题标题】:Replace the string for each occurrence in php?替换php中每次出现的字符串?
【发布时间】:2012-12-09 16:27:38
【问题描述】:

我想用 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是只返回字符串匹配的地方。它不会用指定的特定匹配项替换字符串。那么有什么方法可以完成这个任务吗?

【问题讨论】:

标签: php string replace str-replace


【解决方案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));
}

Here's a demo.

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2021-11-24
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2015-04-27
    相关资源
    最近更新 更多