Last active
August 23, 2018 13:27
-
-
Save nullthoughts/35db66c85661bb1ca908cafc98c55ad8 to your computer and use it in GitHub Desktop.
PHP function to return string between two strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get the portion of a string between two given strings. | |
* | |
* @param string $subject | |
* @param string $start | |
* @param string $end | |
* @param bool $insensitive | |
* @param bool $innerOnly | |
* @param bool $inverse | |
* | |
* @return string | |
*/ | |
public static function between($string, $start, $end, $insensitive = false, $innerOnly = true, $inverse = false) | |
{ | |
if ($insensitive) { | |
$string = strtolower($string); | |
$start = strtolower($string); | |
$end = strtolower($end); | |
} | |
if (($startPosition = strpos($string, $start)) === false || ($endPosition = strpos($string, $end)) === false) { | |
return false; | |
} | |
if ($innerOnly) { | |
$startPosition += strlen($start); | |
$endPosition -= strlen($end); | |
} | |
$between = substr($string, $startPosition, ($endPosition + strlen($end)) - $startPosition); | |
if ($inverse) { | |
return str_replace($between, '', $string); | |
} | |
return $between; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment