0

次のような文字列からユーザーIDを取得しようとしています。

http://www.abcxyz.com/123456789/

123456789として表示するには、基本的に最初の/までの情報を削除し、最後の/も削除します。私はネットで周りを見回しましたが、非常に多くの解決策があるようですが、開始と終了の両方に答えるものは何もありません。

ありがとう :)

アップデート1

リンクは、上記のmod_rewriteと「http://www.abcxyz.com/profile?user_id=123456789」の2つの形式をとることができます。

4

5 に答える 5

3

parse_url()URL からパス コンポーネントをきれいに抽出するために使用します。

$path = parse_URL("http://www.example.com/123456789/", PHP_URL_PATH);

次に、次を使用してパスを要素に分割しますexplode()

$path = trim($path, "/"); // Remove starting and trailing slashes
$path_exploded = explode("/", $path);

次に、パスの最初のコンポーネントを出力します。

echo $path_exploded[0]; // Will output 123456789

この方法は、次のようなエッジケースで機能します

  • http://www.example.com/123456789?test
  • http://www.example.com//123456789
  • www.example.com/123456789/abcdef

そしてさえ

  • /123456789/abcdef
于 2010-10-28T10:06:38.920 に答える
1
$string = 'http://www.abcxyz.com/123456789/';
$parts = array_filter(explode('/', $string));
$id = array_pop($parts);
于 2010-10-28T10:07:26.533 に答える
0

ドメインに番号が含まれていない場合は、次を使用して両方の状況(user_idの有無にかかわらず)を処理できます。

<?php

$string1 = 'http://www.abcxyz.com/123456789/';
$string2 = 'http://www.abcxyz.com/profile?user_id=123456789';

preg_match('/[0-9]+/',$string1,$matches);
print_r($matches[0]);


preg_match('/[0-9]+/',$string2,$matches);
print_r($matches[0]);


?>
于 2010-10-28T10:43:56.800 に答える
0

URLに他の番号がない場合は、次のこともできます

echo filter_var('http://www.abcxyz.com/123456789/', FILTER_SANITIZE_NUMBER_INT);

数字ではないものをすべて取り除きます。

parse_url+のparse_str組み合わせを使用するよりも多少速いかもしれません。

于 2010-10-28T10:14:05.553 に答える
0

ID が常に URL の最後のメンバーである場合

$url="http://www.abcxyz.com/123456789/";
$id=preg_replace(",.*/([0-9]+)/$,","\\1",$url);
echo $id;
于 2010-10-28T10:16:53.347 に答える