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)
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));
}
}
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
?>
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];
}
}
}
If you need equivalent only for SUBSTRING_INDEX(str, delim, 1), you can use:
list($str,) = explode($delim, $str);
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));
}
}
精彩评论