How can I retrieve all characters before the last dash (‘-’) in a string?

Solution:1

To extract everything before the last dash (-), use strrpos() to locate the final dash and substr() to cut the string up to that position:


$output = substr($number, 0, strrpos($number, '-'));

$number → your input string.

strrpos($number, ‘-‘) → finds the position of the last dash.

substr(…) → returns the substring from the beginning up to (but not including) that last dash.

Solution:2
A shorter version of the same approach is:


$part = substr($number, 0, strrpos($number, "-"));

This does the same as Solution 1:

Finds the position of the last – with strrpos().

Extracts everything before it using substr().

Solution:3

You can also combine strrpos() and substr() directly to capture everything before the last dash:


$lastPart = substr($number, 0, strrpos($number, '-'));

strrpos() → locates the final occurrence of -.

substr() → extracts all characters up to (but not including) that position.