我想知道如何在php中替换字符串中的第二个实例,例如以下示例:
a - b - c
当它找到两个"-
"时,会在第二个"-
"后添加一个额外的空格。
$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
使用 strpos
从第一个破折号的索引开始截取字符串,然后对剩余的字符串进行 str_replace
。将两个字符串连接在一起。