2012-08-10 173 views
0

我想提取一個字符串的最後一個單詞,但忽略它可能有的任何擴展名 例如amazon_uk代替amazon_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 
+0

是它始終將是該格式(即URI)? – PeeHaa 2012-08-10 23:01:51

+0

@Petra yes always – 2012-08-10 23:02:28

+0

在這些情況下使用'parse_url()'有些東西需要說明,至少要做第一遍解析。 – 2012-08-10 23:05:56

回答

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

下面是它在做什麼...

/ 

匹配正斜槓

([^./]+) 

然後一個或多個既不是週期或正斜槓的。這是我們匹配的一點。

\. 

然後過一段

[^./]+ 

然後一個或多個既不是週期或斜線再次的。

$ 

然後串


結束時,你問一個正則表達式,所以這上面。但這裏是我真正做...

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

Basename的東西,我用所有的時間 - 非常方便。

+0

我不明白這是什麼... – 2012-08-10 23:04:44

+0

這不就是你問這個問題的原因嗎? – 2012-08-10 23:05:44

+1

正確,但這不工作... http://regexr.com?31q7f – 2012-08-10 23:07:15

1
preg_match('/\/([\w]+)\.(?:[a-zA-Z]{1,3})$/', $str, $matches); 
$result = $matches[1]; 
+0

不完全是我想要的,我想在最後一個正斜槓之後和.gif擴展之前得到這個字符串這個返回是什麼?/ amazon_uk.gif' – 2012-08-10 23:11:43

+0

它返回* amazon_uk *爲我。 嘗試忽略第二行並查看'var_dump($ matches)' – 2012-08-10 23:14:09

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, '.')); 
0

非貪婪搜索再加上擴展可選的比賽應該做的伎倆:

preg_match('/([^\.\/]+?)(?:\.\w*)?$/', $str, $matches); 
$website = $matches[1];