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
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 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));
}
}
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];
}
}
}
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
?>