2014-07-09 34 views
2

我有这样的代码这里之前:PHP获得字符串都强调

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

这让我的一切下划线后,但我希望得到下划线之前的一切,我将如何调整这个在下划线之前获取所有内容的代码?

$fileinfo['basename']等于 'feature_00'

感谢

+0

第一个下划线之后?如果你有多个下划线怎么办? – Ray

回答

9

你应该使用简单:

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

我看不出有任何理由使用explode创造额外的阵列刚刚拿到第一要素。

您也可以使用(在PHP 5.3+):

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

我认为这样做最简单的方法是使用explode

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

这会将字符串拆分为一个子字符串数组。数组的长度取决于有多少个实例_。例如

"one_two_three" 

将被分成数组

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

这里的some documentation

3

如果您完全确定有总是至少有一个下划线,你有兴趣的第一种:

​​

其他的方式可以这样做:

$str = "this_is_many_underscores_example"; 

$matches = array(); 

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

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

(可能regexp模式将需要调整,但为了这个例子的目的,它工作得很好)。

1

如果你想在你的建议是什么类型的一个老派的答案你仍然可以做到以下几点:

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