7

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.

Sebastian
  • 3,548
  • 18
  • 60
  • 95
  • Why non-regex ? its one of the most wonderful things in programming. You can use it for so much?! – Xatenev Apr 10 '14 at 19:25
  • Possible duplicate of [How to remove everything before the first specific character in a string?](https://stackoverflow.com/questions/5329866/how-to-remove-everything-before-the-first-specific-character-in-a-string) – kenorb Nov 21 '18 at 13:25

3 Answers3

13

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.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

For your example, this would work:

$str="£10.00 - £20.00";
$arr=explode(" - ",$str);
echo $arr[1];
Ko Cour
  • 929
  • 2
  • 18
  • 29
-3

Use substr().

$string = "£10.00 - £20.00";
$result = substr($string, -6);
echo $result;
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
  • 3
    this is a bad answer it solve this case only - what will happen if its : $string = "£9.00 - £20.00"; – ohadsas Dec 23 '18 at 14:06