2

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.

4 Answers 4

5

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];
Sign up to request clarification or add additional context in comments.

4 Comments

Typical. You don't know a PHP function exists until you needed it an hour before.
Will be better to use in-built parameters as I wrote below.
@RReverser Your solution works only if the path is "/pagename", but if it's "/path/to/pagename" it will return the wrong result
Don't agree. substr(parse_url('https://www.facebook.com/path/to/pagename?sk=wall&filter=2', PHP_URL_PATH), 1) returns path/to/pagename as is expected. As I understood, author needs all the pathname and not only last part.
2

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.

1 Comment

Would have been a great comment.
1

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

1 Comment

Damn, beat me to it by 20 seconds! Good going :)
0

Use smth like:

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

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.