Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: best method to trim a substring from a string

Tags:

string

php

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

like image 387
shealtiel Avatar asked Jan 09 '11 02:01

shealtiel


People also ask

How do I trim a string after a specific character in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How do you remove portion of a string before a certain character in PHP?

You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.

How do I slice a string in PHP?

PHP: substr() function The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.

Does PHP trim Remove newline?

Yes it does, see the manual: This function returns a string with whitespace stripped from the beginning and end of str .


2 Answers

ima go with preg_replace on this one.

$output = preg_replace('/myEnding$/s', '', $input);
like image 137
dqhendricks Avatar answered Oct 04 '22 20:10

dqhendricks


Try this:

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

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

ideone

like image 27
Mark Byers Avatar answered Oct 04 '22 19:10

Mark Byers