2014-01-15 43 views
0

試圖找出一種方法來在PHP中執行字符串操作。在下面的示例中,我需要識別[backspace]的所有實例並將它們從字符串中移除,但是我也需要在它之前立即移除該字符。PHP字符串操作 - 替換和刪除字符

$string = "this is a sentence with dog[backspace][backspace][backspace]cat in it"; 

會變成「這是一個帶貓的句子」。

我最初的想法是將字符串轉換爲一個數組,並以某種方式執行操作,因爲我不相信有任何方法可以通過str_replace執行此操作。

$array = str_split($string); 

foreach($array as $key) 
{ 
    .. lost here 
} 
+0

所以你說你需要將'[backspace]'作爲一個文字的退格操作?那麼既然你在這裏有3個連續刪除'd-o-g'? –

+0

您不能在這裏使用查找替換解決方案,因此您必須將其作爲代碼實際運行,因此當檢測到[backspace]時,它會在刪除之前刪除1個字母。 – SSpoke

+0

正確的邁克......它會將其視爲文字退格。我只是用backspace作爲例子,但其他的我也會添加到字符串中。 – user756659

回答

3
<?php 
$string = "this is a sentence with dog[backspace][backspace][backspace]cat in it"; 
do{ 
$string = preg_replace('~[^]]\[backspace\]~', '', $string, -1, $count); 
} while($count); 

echo $string; 

如果你不使用文字後退鍵,然後同樣的概念 -

$string = "this is a sentence with dogXXXcat in it"; 


do{ 
    $string = preg_replace('~[^X]X~', '', $string, -1, $count); 
} while($count); 

echo $string; 
+0

這似乎工作!謝謝! – user756659

0

好吧,這不是一個很好的解決方案的整體,但我發現退格鍵可以表示爲一個字符在PHP中。

$string = str_replace("[backspace]", chr(8), $string); 

這對於一個網頁瀏覽器,它會顯示一個奇怪的字符輸出不會工作,適用於在命令提示符下使用PHP雖然。

0

我認爲你可以創建一個循環,直到沒有更多的退格出現,將其第一個實例與前面的字符一起刪除。

function perform_backspace ($string = '') { 
    $search = '[backspace]'; 
    $search_length = strlen($search); 
    $search_pos = strpos($string, $search); 
    while($search_pos !== false) { 
     if($search_pos === 0) { 
      // this is beginning of string, just delete the search string 
      $string = substr_replace($string, '', $search_pos, $search_length); 
     } else { 
      // delete character before search and the search itself 
      $string = substr_replace($string, '', $search_pos - 1, $search_length + 1); 
     } 
     $search_pos = strpos($string, $search); 
    } 
    return $string; 
}