Aaron R
Aaron R

Reputation: 233

Remove the filename and its parent directory from a URL path string

I have this code:

$cl_posturl = "https://post.craigslist.org/".str_replace('"','',$result[FORM][0][ACTION]);

echo $cl_posturl."<br>\n";

It is returning

post.craigslist.org//sdo/S/ctd/csd/x/9FMALgak4Td10Bol/XRk68

it use to return

post.craigslist.org//sdo/S/ctd/csd/x/

How can I modify the code to return it without those 2 last paths?

Upvotes: -2

Views: 224

Answers (2)

mickmackusa
mickmackusa

Reputation: 48049

I would use a regular expression to isolate the last two portions of the url path.

Code: (Demo)

$result['FORM'][0]['ACTION'] = 'post.craigslist.org//sdo/S/ctd/csd/x/9FMALgak4Td10Bol/XRk68';

echo preg_replace('#[^/]*/[^/]*$#', '', $result['FORM'][0]['ACTION']);

Output: post.craigslist.org//sdo/S/ctd/csd/x/

Upvotes: -1

NWCoder
NWCoder

Reputation: 5266

Hey broken this into a few steps for easy reading, but it can be condensed into a single call once you understand it.

$initialString = '/sdo/S/ctd/csd/x/9FMALgak4Td10Bol/XRk68';
$removeOneLevel = substr($initialString, 0, strrpos($initialString, '/'));
$removeSecondLevel = substr($removeOneLevel, 0, strrpos($removeOneLevel, '/'));

$finalUrl = "https://post.craigslist.org".str_replace('"','', $removeSecondLevel);
echo $finalUrl . "\n";

Hope that helps.

Upvotes: 1

Related Questions