Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything up to and including character in PHP string

Tags:

string

php

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.

like image 654
Sebastian Avatar asked Apr 10 '14 19:04

Sebastian


People also ask

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 can I remove all characters from a specific character in PHP?

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.

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 I remove all characters from a string after a specific character?

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.


1 Answers

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.

like image 64
Amal Murali Avatar answered Sep 28 '22 19:09

Amal Murali