0

I need to get the last three parts of a string (url). No need to pull the url from the browser as I already grab it from the database.

So, the string looks like: www.mysite.com/uploads/09/03/myimage.png

The part I'd like to extract from the string is "09/03/myimage.png"

3
  • try print_r($_SERVER) to find related values Commented Sep 9, 2015 at 5:29
  • The url is being pulled from the database and not from $_SERVER, so in this case I need to look through the string and grab the last part mentioned in question. Commented Sep 9, 2015 at 5:30
  • If its a valid url then you can simply use parse_url but as its not a valid url you need to use regex or explode function instead Commented Sep 9, 2015 at 5:33

3 Answers 3

3
<?php
 $url="www.mysite.com/uploads/09/03/myimage.png";
 $values=explode("/",$url); // this will split url string to array based on "/"char
 $length=sizeof($values); //calculated array length
 $lastthreeStringsCombined=$values[$length-3].'/'.$values[$length-2].'/'.$values[$length-1]; // formed new string by combining last 3 array elements
 echo $lastthreeStringsCombined;
?>
Sign up to request clarification or add additional context in comments.

2 Comments

describe what you did and why, don't just dump some code.
@IntricatePixels The best solution is by mapek.
2

Try this:

$lastThreeParts = implode('/', array_slice(explode('/', $url), -3, 3, true));

Comments

1

I'm assuming you want to pull out just the path part and ignore query parameters or hash values in the URL.

I would suggest using parse_url() (documented here: http://php.net/manual/en/function.parse-url.php) to pull out the path.

$url = 'www.mysite.com/uploads/09/03/myimage.png';
$path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $path);
$output = array_slice($parts, -3, 3);
var_dump($output);

This will provide you with an array of the last 3 parts of the path and handles cases like query strings and hash values in the array, of course you will still need to do basic length validation to ensure this logic still holds.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.