替换字符串的第二个实例

3
我想知道如何在php中替换字符串中的第二个实例,例如以下示例:
a - b - c

当它找到两个"-"时,会在第二个"-"后添加一个额外的空格。

4个回答

7
$finds = explode('-', "a - b - c");
if (count($finds) == 3) {
  $finds[2] = " {$finds[2]}";
}

$finds = implode('-', $finds);

1
+1 -- 发布了相同的回复(现已删除),但太晚了 :). 不过你想纠正一下你的最后一行。像这样,$result=implode("-",$finds); - David V.
哈哈,是的,我已经不得不编辑了,因为我错过了explode函数的第二个参数。 - Seaux

1
$str ="a - b - c";    
if (substr_count($str,"-")>2){
  print preg_replace("/^(.*)-(.*)-(.*)/","\\1-\\2- \\3",$str);
}

1
**// User Function to replace string by Occurance**

function str_occ_replace($from,$to,$subject,$occ){
    $myArray = explode($from,$subject);
    print_r($myArray);
    $mystring = '';
    $index = 1;
    foreach($myArray as $ele){

        if($index !== $occ AND $index !== $arraySize)
            $mystring .= $ele.$from;
        else if($index !== $arraySize)
            $mystring .= $ele.$to;
        $index++;
    } // End of Foreach
    return $mystring;
} // End of Function

0

使用 strpos 从第一个破折号的索引开始截取字符串,然后对剩余的字符串进行 str_replace。将两个字符串连接在一起。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接