Home > Mobile >  PHP delete the last word in string by specific word
PHP delete the last word in string by specific word

Time:10-23

How can i delete the last word by a specific word in a string?

So example, this is the string

$string = 'bla test bla test bla test bla test bla'

Now i want to delete test but just the last one, not everyone. Output must be this

$string = 'bla test bla test bla test bla bla'

i just find str_replace and something, but than i delete every test and not only the last one... I also searched here but not finding something to delete the specific word that i will delete. Jsut find something with trim last space or something. But AFTER the last word i search for, there can be more words

CodePudding user response:

Try this:

$string = 'bla test bla test bla test bla test bla';

echo preg_replace('~ test(?!.* test)~', '', $string);

CodePudding user response:

You could try:

<?php
$string = 'bla test bla test bla test bla test bla';
$word = 'test';
echo strrev(preg_replace('/'.preg_quote(' '.strrev($word).' ', '/').'/', ' ', strrev($string), 1));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using the provided String Function strrpos() Find needle in string processing from right to left.

and str_replace() you can do this quite simply

$string = 'bla test bla test bla test bla test bla';
$needle = 'test';
echo $string . PHP_EOL;
$pos = strrpos($string, $needle, 0);
if ( $pos !== FALSE ){
    // it was found in the string
    $new_string = substr_replace($string, '', $pos, strlen('test '));
} else {
    echo "$needle not found in the string";
}
echo $new_string .PHP_EOL;

RESULT

bla test bla test bla test bla test bla
bla test bla test bla test bla bla

CodePudding user response:

A manual way of doing it would be to split the string with a separator into an array, detect last subject position (in reverse), then unset and glue it back together.

var_dump(remove_last('bla test bla test bla test bla test bla', 'test', ' '));

function remove_last(string $text, string $subject, string $separator): string {
    $parts = explode($separator, $text);
    $pos = count($parts) -1 -array_search($subject, array_reverse($parts));

    if ($parts[$pos] ?? false) {
        unset($parts[$pos]);
    }

    return implode($separator, $parts);
}

https://3v4l.org/X0F13

Another way using substr_replace():

var_dump(remove_last('bla test bla test bla test bla test bla', 'test', ' '));

function remove_last(string $text, string $subject, string $separator): string {
    if (($offset = strrpos($text, "$separator$subject")) === false) {
        $offset = strrpos($text, "$subject$separate");
    }
    
    if ($offset !== false) {
        return substr_replace($text, '', $offset, strlen("$separator$subject"));
    }
    
    return $text;
}

https://3v4l.org/ZUULc

  •  Tags:  
  • php
  • Related