Skip to content

Instantly share code, notes, and snippets.

@kagg-design
Last active December 9, 2018 11:32
Show Gist options
  • Select an option

  • Save kagg-design/fef37dbf279bed711627e177273e96b0 to your computer and use it in GitHub Desktop.

Select an option

Save kagg-design/fef37dbf279bed711627e177273e96b0 to your computer and use it in GitHub Desktop.
Finds a substring between two strings.
<?php
/**
* Finds a substring between two strings.
*
* @param string $string The string to be searched
* @param string $start The start of the desired substring
* @param string $end The end of the desired substring
* @param bool $greedy Use last instance of`$end` (default: false)
*
* @return string
*/
function kagg_get_between( $string, $start, $end, $greedy = false ) {
$start = preg_quote( $start, '/' );
$end = preg_quote( $end, '/' );
$format = '/(%s)(.*';
if ( ! $greedy ) {
$format .= '?';
}
$format .= ')(%s)/';
$pattern = sprintf( $format, $start, $end );
preg_match( $pattern, $string, $matches );
return $matches[2];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment