PHP get everything in a string before underscore

user3723240 picture user3723240 · Jul 9, 2014 · Viewed 10.5k times · Source

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

Answer

Marcin Nabiałek picture Marcin Nabiałek · Jul 9, 2014

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);