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
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.
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.
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.
Yes it does, see the manual: This function returns a string with whitespace stripped from the beginning and end of str .
ima go with preg_replace on this one.
$output = preg_replace('/myEnding$/s', '', $input);
Try this:
$s = "foobarmyEnding";
$toRemove = "myEnding";
$len = strlen($toRemove);
if (strcmp(substr($s, -$len, $len), $toRemove) === 0)
{
$s = substr($s, 0, -$len);
}
ideone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With