2010-03-10 221 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