views:

138

answers:

3

Hey, 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 would add an extra space after the second "-" but only if it finds 2.

Thanks

A: 

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.

Pierre-Antoine LaFayette
+2  A: 
$finds = explode('-', "a - b - c");
if (count($finds) == 3) {
  $finds[2] = " {$finds[2]}";
}

$finds = implode('-', $finds);
ocdcoder
+1 -- Posted the same reply (now deleted) but way too late :). You want to correct your last line though. like, $result=implode("-",$finds);
David V.
haha yea, i already had to edit bc i missed the 2nd arg in explode lol.
ocdcoder
A: 
$str ="a - b - c";    
if (substr_count($str,"-")>2){
  print preg_replace("/^(.*)-(.*)-(.*)/","\\1-\\2- \\3",$str);
}
ghostdog74
this doesn't work if there is more than 3
ocdcoder
then add a check for that.
ghostdog74