shealtiel
shealtiel

Reputation: 8388

PHP: best method to trim a substring from a string

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

Upvotes: 11

Views: 11588

Answers (3)

Mike Sherman
Mike Sherman

Reputation: 13

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

Upvotes: -6

dqhendricks
dqhendricks

Reputation: 19251

ima go with preg_replace on this one.

$output = preg_replace('/myEnding$/s', '', $input);

Upvotes: 15

Mark Byers
Mark Byers

Reputation: 837916

Try this:

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

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

ideone

Upvotes: 7

Related Questions