Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: equivalent of MySQL's function SUBSTRING_INDEX ?

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 equivalent of this function in PHP? (or an easy way to do it with a bit of code)

like image 914
Dylan Avatar asked Jul 30 '11 20:07

Dylan


People also ask

What is Substring_index in MySQL?

SUBSTRING_INDEX() function in MySQL is used to return a substring from a string before a specified number of occurrences of the delimiter.

How SUBSTRING INDEX works?

The SUBSTRING_INDEX() function returns a substring of a string before a specified number of delimiter occurs.

Which function would a portion of a string to the left of a specified delimiter occurrence?

SUBSTRING_INDEX() function The substring returned from the left of the final delimiter when the specified number is a positive number and from the right of the final delimiter when the specified number is a negative number.


1 Answers

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));
    }
}
like image 72
Mark Elliot Avatar answered Oct 14 '22 00:10

Mark Elliot