I know this question has several answers but I thought I could also post a concise code which can solve the issue of the OP
function get_string_between( $str, $start, $end ){
return trim( explode( $end, explode( $start, $str )[count( explode( $start, $str ) ) - 1] )[0] );
}
echo $id = get_string_between( "[modid=256]", "=" , "]" );
What is happening here is first splitting the string with the $start
character, or the $start
string, then grabbing the last element of the resulting array, for example, in our case, we have [modid=256]
, we are supposed to get the string between =
and ]
, so we first split our string with =
and get the last element of resulting array, so we get 256]
, finally we explode the remaining string whenever find the last character ]
and grab the first element of the resulting array which will be 256
. This example can get any string between any two strings or characters seamlessly.
If the native functions are too many we can try using the array_pop()
function to get the last element of an array for example:
function get_string_between( $str, $start, $end ){
$first_array = explode( $start, $str );
return trim( explode( $end, array_pop( $first_array ) )[0] );
}
echo $id = get_string_between( "[modid=256]", "=" , "]" );
Also trim
is optional. By using trim()
I'm able to get the spaces on both ends removed.
Also, it would be great to check if the two splitting characters or the two splitting strings exist in your initial string
DEMO