Search code examples
phpstringsubstringtruncation

Strip all characters in a string starting from the second occurring hyphen


How can I strip everything in a string after the character - has occurred for the second time?

For example: Today is - Friday and tomorrow is - Saturday

I want Saturday to be removed along with the last hyphen: - Saturday

I can only seem to get everything to be removed after the first -.

The expected result is: Today is - Friday and tomorrow is


Solution

  • Edit: Please note as noted by @mickmackusa below, this will return an empty string if there are less than two hyphens. End Edit.

    Use strpos to find the first occurrence and use it again to find the point to end using the offset option with the value from previous. Then use substr.

    $newstr = substr($str, 0, strpos($str, '-', strpos($str, '-')+1));