2010-03-10 220 views
3
的二审

我只是想知道我怎么能替换字符串的第二个实例在字符串中的PHP如如下:替换字符串

a - b - c 

凡woulld第二个“-”后面加一个额外的空间但前提是它找到2.

回答

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

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

+1 - 发布了同样的答复(现已删除),但太晚:)。你想纠正你的最后一行。 like,$ result = implode(“ - ”,$ finds); – 2010-03-10 21:46:13

+0

哈哈是啊,我已经不得不编辑BC了,我错过了第二次参照爆炸哈哈。 – Seaux 2010-03-11 00:31:52

0

子串字符串从第一个破折号的索引处开始,使用strpos,然后对该字符串的其余部分执行str_replace。连接在一起。

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

如果超过3 – Seaux 2010-03-11 00:32:47

+0

,则不起作用,然后为其添加检查。 – ghostdog74 2010-03-11 00:45:51

1
**// 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 
+0

此代码完美起作用。 BOL。 – 2017-05-18 07:58:56