PHP: equivalent of MySQL's function SUBSTRING_INDEX ?

前端 未结 5 492
南方客
南方客 2021-01-18 01:20

I love the SUBSTRING_INDEX function in MySQL, especially because you can use negative indexes to start searching from the right side of the string.

Is there an equiv

5条回答
  •  别那么骄傲
    2021-01-18 01:46

    I was curious and tested another method using a preg/match setup, then refactored it to allow for any number of delimiters/count. I added in the count check the other example was using, but I would probably also recommend some kind of sanitization of the delimiter field.

    function substring_index($subject, $delim, $count){
      if($count < 0){
        $notRe = '[^\\'.$delim.']*';
        $elem = array();
        for($x=1;$x<=$count;$x++){
          array_push($elem,$notRe);
        }
        $re = '/^('.implode('\\'.$delim,$elem).')/';
        preg_match($re, $subject,$m);
        if(count($m) == 2) {
          return $m[1];
        }
      }
    }
    

提交回复
热议问题