子串提取。 在前一个'/'之前获取字符串

I am trying to extract a sub-string. I need some help with doing it in PHP.

Here are some sample strings I am working with and the results I need:

$temp = "COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"

And the result i need is:

$temp = d02c25b2-5c07-11e9-8f1a-02fd8bf7d052

I want to get the string at my last '/'

So far, I've tried:

substr($temp, 0, strpos($temp, '/'))

But, it seems didn't work at all.

Is there a way to handle that case with PHP approach ?

You can use substr() to extract the data, but using strrpos() instead to find the last / position (you have to remove the trailing / to do this though)

$temp = "assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/";
// Trim off trailing / or "
$temp = rtrim($temp, "/\"");
// Return from the position of the last / (+1) to the end of the string
$temp = substr($temp, strrpos($temp, '/')+1);
echo $temp;

gives...

d02c25b2-5c07-11e9-8f1a-02fd8bf7d052

You can do it with explode() and end() functions.

Steps Explained:

1) Explode() the string by /

2) Replace double quotes ".

3) array_filter() to remove blank elements.

4) end() for the last element as / and empty element after last / are already removed.

Code:

<?php 
$temp = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
$temp = str_replace('"', '', $temp);
$url = explode('/', $temp);
$url = array_filter($url);
$requiredSegment = end($url);

echo '<pre>';
print_r($requiredSegment);
echo '</pre>';

Output:

d02c25b2-5c07-11e9-8f1a-02fd8bf7d052

See it live here:

Simply try this code snippet

$temp = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
$temp = rtrim(str_replace('celc_coba/','',strstr($temp, 'celc_coba/')), "/\"")

Result

d02c25b2-5c07-11e9-8f1a-02fd8bf7d052

You can do this by:explode

$str = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';
$pieces = explode("/", $str );

example

$str = '"COM1904150001","1","ytuaioeighalk","tyueiff","assets/report/celc_coba/d02c25b2-5c07-11e9-8f1a-02fd8bf7d052/"';

$pieces = explode("/", $str );

print_r($pieces);


$count= count($pieces);


echo  $pieces[$count-2];

Codepad