Search code examples
phpstringsubstrstrpos

PHP get everything in a string before underscore


I have this code here:

$imagePreFix = substr($fileinfo['basename'], strpos($fileinfo['basename'], "_") +1);

this gets me everything after the underscore, but I am looking to get everything before the underscore, how would I adjust this code to get everything before the underscore?

$fileinfo['basename'] is equal to 'feature_00'

Thanks


Solution

  • You should simple use:

    $imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));
    

    I don't see any reason to use explode and create extra array just to get first element.

    You can also use (in PHP 5.3+):

    $imagePreFix = strstr($fileinfo['basename'], '_', true);