Robbie Dc
Robbie Dc

Reputation: 701

Using rtrim in php for specific purpose

I am not much used to using rtrim and Reg expressions. So I wanted to get my doubt cleared about this:

Here is a url: http://imgur.com/r/pics/paoWS

I am trying to use rtrim function on this url to pick out only the 'paoWs' from the whole url. Here is what i tried:

$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);

$yid=rtrim( $video_id, '/' );

And i am using '$yid' to hotlink the image from imgur. But What I get after trying this function is:

$yid= '/r/pics/paoWS'

How do I solve this?

Upvotes: 0

Views: 169

Answers (4)

Narf
Narf

Reputation: 14752

rtrim() returns the filtered value, not the stripped characters. And your usage of it isn't proper too - it strips the passed characters from the right side. And you don't need parse_url() either. Proper answers have been given already, but here's a faster alternative:

$yid = substr($yurl, strrpos($yurl, '/')+1);

Edit: And another one:

$yid = ltrim(strrchr($yurl, '/'), '/');

Upvotes: 1

Mona Abdelmajeed
Mona Abdelmajeed

Reputation: 686

rtim( strrchr('http://imgur.com/r/pics/paoWS' , '/') );   rtrim + strrchr
substr(strrchr('http://imgur.com/r/pics/paoWS', "/"), 1);  substr + strrchr

Upvotes: 1

berty
berty

Reputation: 2206

You sould not use regular expressions (whitch are 'expensive') for a so 'simple' problem.

If you want to catch the last part of the URL, after the last slash, you can do :

$urlParts = explode('/', 'http://imgur.com/r/pics/paoWS');
$lastPart = end($urlParts);

Upvotes: 2

BenM
BenM

Reputation: 53198

rtrim is used for trimming down a string of certain characters or whitespace on the right-hand side. It certainly shouldn't be used for your purpose.

Assuming the URL structure will always be the same, you could just do something like this:

$yurl = 'http://imgur.com/r/pics/paoWS'; 
$video_id = parse_url($yurl, PHP_URL_PATH);
$parts = explode('/', $video_id)
$yid = end($parts);

Upvotes: 4

Related Questions