11

Want to process a set of strings, and trim some ending "myEnding" from the end of each string if it exists.

What is the simplest way to do it? I know that everything is possible with regexp, but thus seems to be a simple task, and I wonder whether a simpler tool for this exists.

Thanks

Gidi

1

3 Answers 3

15

ima go with preg_replace on this one.

$output = preg_replace('/myEnding$/s', '', $input);
Sign up to request clarification or add additional context in comments.

5 Comments

Tanks for the valuable answer, even though I asked for non regexp solutions
you asked for the simplest way to do it. in this case, regex was the simplest way.
Regexp is a hero :)
If your string to remove (e.g., myEnding) is from user input or otherwise can't be trusted, be sure to use preg_quote(). So, something like this: $output = preg_replace('/' . preg_quote($myEnding) . '$/s', '', $input);
I'm willing to bet this is the slower solution, regexp is not really efficient for simple tasks like this.
7

Try this:

$s = "foobarmyEnding";
$toRemove = "myEnding";

$len = strlen($toRemove);
if (strcmp(substr($s, -$len, $len), $toRemove) === 0)
{
    $s = substr($s, 0, -$len);
}

ideone

1 Comment

This is probably much faster than regex for such a simple task.
-6

rtrim http://php.net/manual/en/function.rtrim.php

$str = "foobarmyEnding";
$str = rtrim($str, 'myEnding');
// str == "foobar"

ltrim is the same deal for the start of a string http://php.net/manual/en/function.ltrim.php

You could also use str_replace to replace a search term with with an empty string but its slower then rtrim/ltrim if you need to amend the start or end of a string

3 Comments

Not really. The second parameter to rtrim is a list of characters to strip. It's not handled as an entire string.
The question was "trim some ending "myEnding" from the END of each string"
If your string contains any of those characters directly before "myEnding", they will get stripped as well. Let me give an example: what happens when you input "HelloMikeShermanmyEnding". You'd expect the output to be "HelloMikeSherman" but the output will be "HelloMikeSherma"! Because "n" is part of the character list provided to rtrim.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.