Replace second row instance

I'm just wondering how I can replace the second instance of a string inside a string in php, for example:

a - b - c

Where he will add extra space after the second " -", but only if he finds 2.

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

$finds = implode('-', $finds);
+7
source
$str ="a - b - c";    
if (substr_count($str,"-")>2){
  print preg_replace("/^(.*)-(.*)-(.*)/","\\1-\\2- \\3",$str);
}
+1
source
**// 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
+1
source

Trim the line starting at the index of the first dash using strpos, then do str_replacethe rest of the line. Put them together.

0
source

Source: https://habr.com/ru/post/1736391/


All Articles