PHP: equivalent MySQL function SUBSTRING_INDEX?

I like the SUBSTRING_INDEX function in MySQL, especially because you can use negative indexes to start the search on the right side of the string.

Is there an equivalent of this function in PHP? (or an easy way to do this with a bit of code)

+6
source share
4 answers

There is no single library function that provides you with the same functionality, but you can get a single line:

 $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" 

It is easy to 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)); } } 
+14
source

I think,

 string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] ) 

is the right php function for you.

strstr - find 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 ?> 
+3
source

I was curious and tested another method using the preg / match setting, and then reorganized it to allow any number of delimiters / counters. I added another example to the checkout counter, but I would probably also recommend some sort of sanitizer field disinfection.

 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]; } } } 
0
source
 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)); } } 
-2
source

Source: https://habr.com/ru/post/893956/


All Articles