PHP: equivalent of MySQL's function SUBSTRING_INDEX ?
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 = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>