Micku
Micku

Reputation: 550

How to get username from an url after matching url with a particular string?

I want to get username from an url after checking the rest of url is similar to a string.

For eg : I need username from the url 'http://mysite.com/username' . before that need to check

site url as 'http://mysite.com/' and also username part contains only alphabets,numbers,

underscore and periods..

How is it possible using php?

Upvotes: 0

Views: 1003

Answers (5)

AmbroseChapel
AmbroseChapel

Reputation: 12097

There are functions for parsing URLs:

http://php.net/manual/en/function.parse-url.php

If you do this:

$url = 'http://mysite.com/username';
$array = parse_url($url);
print_r($array);

You will see this:

Array
(
    [scheme] => http
    [host] => mysite.com
    [path] => /username
)

now you can treat the path of the URL seperately. If there's more to it than just /username/ then you would split on '/' and use the first item returned.

    $path_array = explode('/',$array['path']);

Upvotes: 1

Adrian
Adrian

Reputation: 2875

If you want to try this with regex, you can use a pattern with two capture groups, one for the domain name and one for the username, like so:

^http\:\/\/([^/]+)\/(.+)$

(I escaped the colon there because I honestly can't remember off the top of my head whether or not it's necessary. If not, it doesn't need the escape character)

This will look for http:// followed by a string that doesn't contain a / (so it'll keep grabbing until it reaches the next /) and then expects a / and then grabs anything else that follows up until the end of the string.

Upvotes: 0

米雪儿
米雪儿

Reputation: 71

$url = "http://mysite.com/username";
$arr = parse_url($url);
if($arr['host'] != "mysite.com"){
    // do something 
}
print_r(trim($arr['path'],'/'));

Upvotes: 0

godspeedlee
godspeedlee

Reputation: 672

I have tested with PHP5.4.5:

<?php

$simple = 'http://mysite.com/username';

if ( preg_match('/http:\/\/mysite\.com\/(?:([-\w]+)\/?)/', $simple, $match) > 0){
    echo 'Username is: '.$match[1] . "\n";

}

$complex = 'http://mysite.com.zzz.yyy/john/';
if ( preg_match('/http:\/\/\w+(?:\.\w+)*\/(?:([-\w]+)\/?)/', $complex, $match) > 0){
    echo 'Username is: '.$match[1] . "\n";

}

?>

output:

Username is: username
Username is: john

Upvotes: 1

user849137
user849137

Reputation:

This is what you have:

preg_match('/mysite.com//[a-zA-Z0-9-]';, $user_name, $matches);

You have no delimiter, and what's with the ;? Try this:

preg_match('|/mysite.com//[a-zA-Z0-9-]|', $user_name, $matches);

Upvotes: 0

Related Questions