Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 965
Belgin Fish Avatar asked Jun 25 '26 21:06

Belgin Fish


2 Answers

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

$finds = implode('-', $finds);
like image 145
Seaux Avatar answered Jun 27 '26 12:06

Seaux


$str ="a - b - c";    
if (substr_count($str,"-")>2){
  print preg_replace("/^(.*)-(.*)-(.*)/","\\1-\\2- \\3",$str);
}
like image 40
ghostdog74 Avatar answered Jun 27 '26 13:06

ghostdog74



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!