2012-05-04 10 views
1

私はサイトを持っており、PHPで1ページのURLを取得する必要があります。 URLは何かwww.mydomain.com/thestringineed/でもかまいません。www.mydomain.com/thestringineed?data=1でもかまいません。www.mydomain.com/ss/thestringineedPHPでURLの一部を取得

だから、いつも最後の文字列ですが、何もしたくないのですか?

+0

である私が理解できない、あなたは 'www.mydomain.com'や' '/ thestringineedを取得したいですか? – Mediator

+0

'/ ss/thestringineed'から明確にするためには、あなただけが' thestringineed'を望んでいますか? –

+0

はい、私が必要とするのは弦楽器だけです。 – user1069269

答えて

2

を介して受信することができます。このような :

$url='www.mydomain.com/thestringineed?data=1'; 
$components=parse_url($url); 

//$mystring= end(explode('/',$components['path'])); 

// I realized after this answer had sat here for about 3 years that there was 
//a mistake in the above line 
// It would only give the last directory, so if there were extra directories in the path, it would fail. Here's the solution: 
$mystring=str_replace(reset(explode('/',$components['path'])),'',$components['path']); //This is to remove the domain from the beginning of the path. 

// In my testing, I found that if the scheme (http://, https://, ...) is present, the path does not include 
//the domain. (it's available on it's own as ['host']) In that case it's just 
// $mystring=$components['path']); 
+0

私はそれをテストしなければなりませんが、rtrim($ components ['path']、 '/') 'がスラッシュで終わった場合に備えなければならないかもしれません。私の投稿された答えは、その場合null文字列を返すかもしれません。 – TecBrat

+0

私はこれが速いテストの後で少なくとも動作すると思います。どうも – user1069269

4

parse_urlがお手伝いします。

<?php 
    $url = "http://www.mydomain.com/thestringineed/"; 
    $parts = parse_url($url); 

    print_r($parts); 
?> 
+0

これはOPが望んでいるものではありません。 '/ ss/thestringineed'の場合は、パス部分に' thestringineed'だけでなく、すべてを返します。 –

0

parse_url()は、あなたが探している機能です。あなたがしたい正確な部分は、あなたがリターンのパス部分を見て、その後、でもparse_url関数を使用しますPHP_URL_PATH

$url = 'http://php.net/manual/en/function.parse-url.php'; 
echo parse_url($url, PHP_URL_PATH); 
0

使用$_SERVER['REQUEST_URI']は、それはあなたが「/」でそれを分割し、最後の配列インデックスを使用することができ、完全な現在のページのURLを返します。 URL内のすべての「/」を削除し、すべての単語を含む配列を返します

$strings = explode("/", $urlstring); 

:それは最後の文字列

を使用でき
0

になります。私たちはそれを削除する必要が

$strings[count($strings)-1] 

は、今あなたが必要とする文字列の値を持っていますが、それは含まれていてもよい「データ= 1?」:

$strings2 = explode("?", $strings[count($strings)-1]); 

$strings2[0] 

はあなたの外に欠けている文字列を持っていますurl。

希望の方はこちら!

0
<?php 
$url = 'http://username:[email protected]/path?arg=value#anchor'; 

print_r(parse_url($url)); 

echo parse_url($url, PHP_URL_PATH); 
?> 

とあなたのアウトプットが

Array 
(
    [scheme] => http 
    [host] => hostname 
    [user] => username 
    [pass] => password 
    [path] => /path 
    [query] => arg=value 
    [fragment] => anchor 
) 
/path