user756659
user756659

Reputation: 3512

php string manipulation - replacing and removing characters

Trying to figure out a way to perform string manipulation in php. In the example below I need to recognize all instances of [backspace] and remove them from the string, BUT I also need to remove the character immediately before it as well.

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

would become "this is a sentence with cat in it".

My initial thought was turning the string into an array and performing the operation that way somehow as I don't believe there is any way I could do this with str_replace.

$array = str_split($string);

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

Upvotes: 0

Views: 279

Answers (3)

cyberwombat
cyberwombat

Reputation: 40084

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

If you are not using literal [backspace] then same concept -

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


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

echo $string;

Upvotes: 3

Mike Brant
Mike Brant

Reputation: 71384

I would think you could just create a loop that executes until there are no more backspaces present, taking the first instance of it an deleting it along with the preceding character.

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

Upvotes: 0

SSpoke
SSpoke

Reputation: 5836

Okay this isn't a good solution overall, but I found backspace can be represented as a character in PHP.

Such as

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

This wont work for outputting in a webbrowser it will show up a strange character, works for using PHP in a command prompt though.

Upvotes: 0

Related Questions