user2074836
user2074836

Reputation:

Return a substring between two characters in 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

Upvotes: 0

Views: 496

Answers (6)

VGafurov
VGafurov

Reputation: 14

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

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

Upvotes: 0

Theolodis
Theolodis

Reputation: 5092

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);

Upvotes: 0

zion ben yacov
zion ben yacov

Reputation: 725

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

Upvotes: 0

hsz
hsz

Reputation: 152304

Just try with:

$string = 'numbergrid_21372566/_assets/audio/';
$output = explode('/', $string)[2];

Upvotes: 0

Sahil Mittal
Sahil Mittal

Reputation: 20753

Try-

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

Upvotes: 0

mesutozer
mesutozer

Reputation: 2859

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

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

Upvotes: 3

Related Questions