Pinkie
Pinkie

Reputation: 10256

get a specific part of a string

I have the following url. http://domain.com/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.

Upvotes: 1

Views: 3331

Answers (3)

JRL
JRL

Reputation: 78003

Assuming your string is stored in $s, simply:

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

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

You could, with JavaScript, try:

var string = "http://domain.com/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:

Upvotes: 3

GolezTrol
GolezTrol

Reputation: 116110

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.

Upvotes: 5

Related Questions