Search code examples
phpregexpreg-replacestrpos

Remove the last part of a string after underscore and random digit


My string looks like

$img_name = "my_beautiful_picture_123456_789101112131415_16171819202122.jpg"

What's the easiest way to remove from the first underscore followed by a digit to the end?

I would like to output

my_beautiful_picture

I tried

$img_name = substr($img_name, 0, strpos($img_name, "_"));

and

$img_name = preg_replace('/_[0-9].*/', '', $img_name);

But result is my for both, I'm not very familiar with regex.


Solution

  • We could simply use a simple expression with preg_replace or preg_match or preg_match_all:

    _[0-9].+
    

    Test

    $re = '/_[0-9].+/s';
    $str = 'my_beautiful_picture_123456_789101112131415_16171819202122.jpg';
    $subst = '';
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    Output

    my_beautiful_picture
    

    DEMO

    RegEx Circuit

    jex.im visualizes regular expressions:

    enter image description here