PHP get everything in a string before underscore

前端 未结 4 1839
既然无缘
既然无缘 2020-12-21 10:09

I have this code here:

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

this gets me everything after

4条回答
  •  轮回少年
    2020-12-21 10:43

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

提交回复
热议问题