php字符串操作 - 替换和删除字符

时间:2014-01-15 23:40:07

标签: php string

试图找出一种在php中执行字符串操作的方法。在下面的例子中,我需要识别[backspace]的所有实例并从字符串中删除它们,但我也需要在它之前删除它。

$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
}

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

好的,这不是一个好的解决方案,但我发现退格可以表示为PHP中的一个字符。

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

这不适用于在webbrowser中输出它将显示一个奇怪的字符,但在命令提示符中使用PHP。

答案 2 :(得分: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;
}