Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 297
user3723240 Avatar asked Jul 09 '14 18:07

user3723240


4 Answers

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); 
like image 125
Marcin Nabiałek Avatar answered Oct 16 '22 23:10

Marcin Nabiałek


If you are completely sure that there always be at least one underscore, and you are interested in first one:

$str = $fileinfo['basename'];

$tmp = explode('_', $str);

$res = $tmp[0];

Other way to do this:

$str = "this_is_many_underscores_example";

$matches = array();

preg_match('/^[a-zA-Z0-9]+/', $str, $matches);

print_r($matches[0]); //will produce "this"

(probably regexp pattern will need adjustments, but for purpose of this example it works just fine).

like image 32
ex3v Avatar answered Oct 16 '22 22:10

ex3v


I think the easiest way to do this is to use explode.

$arr = explode('_', $fileinfo['basename']);
echo $arr[0];

This will split the string into an array of substrings. The length of the array depends on how many instances of _ there was. For example

"one_two_three"

Would be broken into an array

["one", "two", "three"] 

Here's some documentation

like image 37
14 revs, 12 users 16% Avatar answered Oct 16 '22 23:10

14 revs, 12 users 16%


If you want an old-school answer in the type of what you proposed you can still do the following:

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

like image 1
Valentin Mercier Avatar answered Oct 17 '22 00:10

Valentin Mercier