PHP: equivalent of MySQL's function SUBSTRING_INDEX ?

前端 未结 5 487
南方客
南方客 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:36

    There's no single library function that gets you this same functionality, but you can get a one-liner:

    $str = "www.mysql.com";
    echo implode('.', array_slice(explode('.', $str), 0, 2)); // prints "www.mysql"
    echo implode('.', array_slice(explode('.', $str), -2));   // prints "mysql.com"
    

    Easily turn this into a function:

    function substring_index($subject, $delim, $count){
        if($count < 0){
            return implode($delim, array_slice(explode($delim, $subject), $count));
        }else{
            return implode($delim, array_slice(explode($delim, $subject), 0, $count));
        }
    }
    
    0 讨论(0)
  • 2021-01-18 01:41

    If you need equivalent only for SUBSTRING_INDEX(str, delim, 1), you can use:

    list($str,) = explode($delim, $str);
    
    0 讨论(0)
  • 2021-01-18 01:45
    function substring_index($subject, $delim, $count){
        if($count < 0){
            return implode($delim, array_slice(explode($delim, $subject), $count));
        }else{
            return implode($delim, array_slice(explode($delim, $subject), 0, $count));
        }
    }
    
    0 讨论(0)
  • 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];
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-18 02:02

    I think

    string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
    

    is the right php function for you.

    strstr — Finds the first occurrence of a string

    <?php
    $email  = 'name@example.com';
    $domain = strstr($email, '@');
    echo $domain; // prints @example.com
    
    $user = strstr($email, '@', true); // As of PHP 5.3.0
    echo $user; // prints name
    ?>
    
    0 讨论(0)
提交回复
热议问题