I'm looking for a non-regex solution (if possible) to the following problem:
I'd like to remove everything up to and including a particular string within a string.
So, for example, £10.00 - £20.00
becomes just £20.00
, maybe by providing the function with -
as a parameter.
I've tried strstr
and ltrim
, but neither were quite what I was after.
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.
The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string.
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.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
This can be achieved using string manipulation functions in PHP. First we find the position of the -
character in the string using strpos()
. Use substr()
to get everything until that character (including that one). Then use trim()
to remove whitespace from the beginning and/or end of the string:
echo trim(substr($str, strpos($str, '-') + 1)); // => £20.00
Alternatively, you could split the string into two pieces, with -
as the delimiter, and take the second part:
echo trim(explode('-', $str)[1]);
This could be done in many different ways. In the end, it all boils down to your preferences and requirements.
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