我有这段代码:
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));
这会让我得到下划线之前的所有字符,如果想得到下划线后面的所有字符,可以使用上一个代码。
$fileinfo['basename']
等于 'feature_00'
谢谢
您应该简单地使用:
$imagePreFix = substr($fileinfo['basename'], 0, strpos($fileinfo['basename'], "_"));
我不认为有任何理由使用explode
并创建额外的数组来获取第一个元素。
您也可以使用(在PHP 5.3+中):
$imagePreFix = strstr($fileinfo['basename'], '_', true);
如果你完全确定至少会有一个下划线,并且你对第一个下划线感兴趣:
$str = $fileinfo['basename'];
$tmp = explode('_', $str);
$res = $tmp[0];
另一种做法:
$str = "this_is_many_underscores_example";
$matches = array();
preg_match('/^[a-zA-Z0-9]+/', $str, $matches);
print_r($matches[0]); //will produce "this"
(可能需要调整正则表达式模式,但就本例而言,它可以正常工作。)
我认为最简单的方法是使用 explode
。
$arr = explode('_', $fileinfo['basename']);
echo $arr[0];
_
实例。例如"one_two_three"
会被分解成一个数组
["one", "two", "three"]
这里是一些文档