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



试图找出一种在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
}
<?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;

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

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

这不适用于在网络浏览器中输出,它会显示一个奇怪的字符,适用于在命令提示符下使用 PHP。

我认为您可以创建一个循环,该循环一直执行直到不再存在退格,将其的第一个实例与前面的字符一起删除。

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

最新更新