在PHP中返回两个字符之间的子字符串

As the title says I need to return a particular part of string that falls between two substrings.

Example:

$string = numbergrid_21372566/_assets/audio/

Now every time, I need to return the part of string that falls between the last two slashes (/) I.E audio in this case.

How can I achieve that? Thanks for reading

You can use explode method to split string from given characters, then use list to match the element you want:

list(,,$var,) = explode('/', $string)

Try-

$parts = explode("/", $string);
$res = $parts[count($parts)-2];

Just try with:

$string = 'numbergrid_21372566/_assets/audio/';
$output = explode('/', $string)[2];
$arr = explode('/',$string);
$firstSegment = $arr[0]; // numbergrid_21372566
$secondSegment = $arr[1]; // _assets
$thirdSegment = $arr[2]; // audio

You could also use the substr method, combined with the strpos method:

$start = strpos($string, "/");
$end = strpos($string, "/", $start);
$length = $end - $start;
$result = substr($string, $start, $length);

If you know that it always would be the last part, you can use array_pop function:

$arr = explode('/', $string);
$result = array_pop($arr);