Is there a way to remove everything before and including the last instance of a certain character?
I have multiple strings which contain >
, e.g.
the > cat > sat > on > the > mat
welcome > home
I need the strings to be formatted so they become
mat
home
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 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 trim : trim($dataList, '*'); This will remove all * characters (even if there are more than one!) from the end and the beginning of the string.
Regex Replace We can also call the string replace method with a regex to remove the part of the string after a given character. The /\?. */ regex matches everything from the question to the end of the string. Since we passed in an empty string as the 2nd argument, all of that will be replaced by an empty string.
You could use a regular expression...
$str = preg_replace('/^.*>\s*/', '', $str);
CodePad.
...or use explode()
...
$tokens = explode('>', $str);
$str = trim(end($tokens));
CodePad.
...or substr()
...
$str = trim(substr($str, strrpos($str, '>') + 1));
CodePad.
There are probably many other ways to do it. Keep in mind my examples trim the resulting string. You can always edit my example code if that is not a requirement.
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