Search code examples
phpstrpos

How to get the characters before the last “-” only if the string after the last "-" is numeric?


Suppose I have string like $string = 'About-Us', then I will get formatted data as $fdata = 'About-Us'

However, if $string = 'About-Us-2', then I will get formatted data as $fdata = 'About-Us' and $remain_data = '2'.

I am using this code:-

$fdata = substr( $string, 0, strrpos( $string, '-' ) );

However, the above code also strips out $fdata = 'About', when $string = 'About-Us'.

How can I cut out string from last "-" only when the last "-" is followed by a numeric string?


Solution

  • You are on the right way. strpos is looking for the last occurrence of a substring.

    So you can just check if the last string is numeric:

    $string = 'About-Us-2';
    $fdata = is_numeric(substr($string, strrpos( $string, '-' )+1, strlen($string))) ? substr( $string, 0, strrpos( $string, '-' ) ) : $string;
    $remain_data = is_numeric(substr($string, strrpos( $string, '-' )+1, strlen($string))) ? substr($string, strrpos( $string, '-' )+1, strlen($string)) : '';
    echo $fdata;
    echo $remain_data;