Joe W
Joe W

Reputation: 1008

Using regex to get string from URL?

Regex is my bete noire, can anyone help me isolate a string from a URL?

I want to get the page name from a URL which could appear in any of the following ways from an input form:

https://www.facebook.com/PAGENAME?sk=wall&filter=2
http://www.facebook.com/PAGENAME?sk=wall&filter=2
www.facebook.com/PAGENAME
facebook.com/PAGENAME?sk=wall

... and so on.

I can't seem to find a way to isolate the string after .com/ but before ? (if present at all). Is it preg_match, replace or split?

If anyone can recommend a particularly clear and introductory regex guide they found useful, it'd be appreciated.

Upvotes: 2

Views: 592

Answers (4)

RReverser
RReverser

Reputation: 2036

Use smth like:

substr(parse_url('https://www.facebook.com/PAGENAME?sk=wall&filter=2', PHP_URL_PATH), 1);

Upvotes: 0

Sven Koschnicke
Sven Koschnicke

Reputation: 6711

For learning and testing regexes I found RegExr, an online tool, very useful: http://gskinner.com/RegExr/

But as others mentioned, parsing the url with appropriate functions might be better in this case.

Upvotes: 2

Sukumar
Sukumar

Reputation: 3577

I think you can use this php function (parse_url) directly instead of using regex.

Upvotes: 1

mck89
mck89

Reputation: 19231

You can use the parse_url function and then get the last segment from the path of the url:

$parts=parse_url($url);
$path_parts=explode("/", $parts["path"]);
$page=$path_parts[count($path_parts)-1];

Upvotes: 5

Related Questions