admin管理员组

文章数量:1405558

I have the following url. .png Everything in the url can change except the userfiles part and the last underscore. Basically I want to get the part of the url which is userfiles/dynamic/images/whatever_dollar_ What is a good way to do this. I'm open or both JavaScript or php.

I have the following url. http://domain./userfiles/dynamic/images/whatever_dollar_1318105152.png Everything in the url can change except the userfiles part and the last underscore. Basically I want to get the part of the url which is userfiles/dynamic/images/whatever_dollar_ What is a good way to do this. I'm open or both JavaScript or php.

Share Improve this question asked Oct 8, 2011 at 20:39 PinkiePinkie 10.2k22 gold badges81 silver badges124 bronze badges 1
  • php/manual/en/function.parse-url.php – dm03514 Commented Oct 8, 2011 at 20:44
Add a ment  | 

3 Answers 3

Reset to default 5

Use parse_url in PHP to split an url in its various parts. Get the path part that is returned. It contains the path without the domain and the query string.

After that use strrpos to find the last occurrance of the _ within the path.

With substr you can copy the first part of the path (up until the found _) and you're done.

You could, with JavaScript, try:

var string = "http://domain./userfiles/dynamic/images/whatever_dollar_1318105152.png";

var newString = string.substring(string.indexOf('userfiles'),string.lastIndexOf('_'));
alert(newString); // returns: "userfiles/dynamic/images/whatever_dollar" (Without quotes).

JS Fiddle demo.

References:

  • substring().
  • indexOf().
  • lastIndexOf().

Assuming your string is stored in $s, simply:

echo preg_replace('/.*(userfiles.*_).*/', '$1', $s);

本文标签: phpget a specific part of a stringStack Overflow