0

文字列の最後の単語を抽出しようとしていますが、拡張子を無視していますamazon_ukamazon_uk.gif

次のコードは、2 つの preg_match 関数を使用して文字列から単語を抽出します。1 つの preg_match 関数で同じことを実行できるようにしたいのですが、どうすればよいですか?

phpコード

$str = 'http://i.example.com/about/bs/logo_borderless/amazon_uk.gif';

preg_match('/[^\.\/]+\.[^\.\/]+$/', $str, $matches);
preg_match('/^[^.]+(?=.)/', $matches[0], $matches2);
$website = $matches2[0];

出力

amazon_uk
4

4 に答える 4

3
preg_match( '#/([^./]+)\.[^./]+$#si', $str, $matches );

これが何をしているのか...

/

スラッシュに一致

([^./]+)

次に、ピリオドまたはスラッシュ以外の 1 つ以上。これは、一致しているビットです。

\.

その後、ピリオド

[^./]+

次に、ピリオドまたはスラッシュ以外の 1 つ以上を再度使用します。

$

次に、文字列の末尾


あなたは正規表現について尋ねたので、それは上にあります。しかし、ここで私が実際に行うことは...

$url = 'http://i.example.com/about/bs/logo_borderless/amazon_uk.gif';
$output = str_replace( array('.gif','.jpg','.png'), '', basename($url) );

Basenameは私がいつも使っているもので、とても便利です。

于 2012-08-10T23:03:32.000 に答える
2

常に (コメントごとに) 指定した形式になるため、substr()strpos()(およびstrrpos()) の組み合わせを使用して、正規表現とは対照的にテキストを取得することもできます。

// get the filename after the last slash
$file = substr($str, strrpos($str, '/') + 1);
// get the text before the extension
$website = substr($file, 0, strpos($file, '.'));
于 2012-08-10T23:07:47.413 に答える
1
preg_match('/\/([\w]+)\.(?:[a-zA-Z]{1,3})$/', $str, $matches);
$result = $matches[1];
于 2012-08-10T23:07:40.447 に答える
0

欲張りでない検索と拡張機能のオプションの一致でうまくいくはずです。

preg_match('/([^\.\/]+?)(?:\.\w*)?$/', $str, $matches);
$website = $matches[1];
于 2012-08-11T00:59:09.643 に答える