PHP Method for getting the middle part of a string

  • 2021-07-13 04:31:43
  • OfStack

This is a substring between two substrings in a string, such as getting coderbolg substring from the string www. ofstack. com, let this PHP function to achieve it, the code is as follows:


function get_between($input, $start, $end) {   $substr = substr($input, strlen($start)+strpos($input, $start),  (strlen($input) - strpos($input, $end))*(-1));   return $substr; } $string = "www.ofstack.com"; $start = "www."; $end = ".net"; echo get_between($string, $start, $end);  // output:coderbolg

However, the limitation of this function is that the $start substring and the $end substring can only appear once in the whole string. Look at the following example:

$string = "https://www.ofstack.com/"; $start = "http://"; $end = "/";

Obviously, I want to get the domain name part of this standard URL. Because the $end substring is not only 1 in the whole string, there will be problems. Please pay attention when using it!


Related articles: