PHP get everything in a string before underscore

蹲街弑〆低调 提交于 2019-12-01 23:09:29

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

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

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

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'], "_"));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!