开发者

Replace Second Instance of String

I just wondering how I could replace the second instance of a string inside a string in php such as follows:

a - b - c

Where开发者_如何学编程 it woulld add an extra space after the second "-" but only if it finds 2.


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

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


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


**// 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


Substring the string starting at the index of the first dash using strpos then do a str_replace on the rest of the string. Concatenate the two together.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜