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)
SUBSTRING_INDEX() function in MySQL is used to return a substring from a string before a specified number of occurrences of the delimiter.
The SUBSTRING_INDEX() function returns a substring of a string before a specified number of delimiter occurs.
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.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With