2013-05-04 34 views
1

請告訴我如何從Google字體網址中輸入preg_match字體名稱。使用正則表達式從Google字體網址獲取字體名稱

例如,我想提取的字體名稱:

http://fonts.googleapis.com/css?family=Oswald:400,300 
http://fonts.googleapis.com/css?family=Roboto+Slab 

,以獲取字體名稱OswaldRoboto Slab

+1

如果你被困在regexs你可以在這裏http://www.regular-expressions.info/ – elclanrs 2013-05-04 09:31:55

+1

開始,你可以只使用這個'str_replace' - 只是刪除'HTTP://字體。 googleapis.com/css?family ='你大部分都在那裏。但是,要給正則表達式一個自己去 - 這是學習的好東西! – halfer 2013-05-04 09:38:30

+0

您是否從HTML或其他來源獲取URL,因爲正則表達式可能不是最佳選擇。可能有點呆滯。 – 2013-05-04 16:06:11

回答

1

這裏是你可能會preg_replace()做一個例子,但是要小心,數據挖掘谷歌。

<?php 
$urls = array("http://fonts.googleapis.com/css?family=Oswald:400,300", 
"http://fonts.googleapis.com/css?family=Roboto+Slab"); 

$patterns = array(
     //replace the path root 
'!^http://fonts.googleapis.com/css\?!', 
     //capture the family and avoid and any following attributes in the URI. 
'!(family=[^&:]+).*$!', 
     //delete the variable name 
'!family=!', 
     //replace the plus sign 
'!\+!'); 
$replacements = array(
"", 
'$1', 
'', 
' '); 

foreach($urls as $url){ 
    $font = preg_replace($patterns,$replacements,$url); 
    echo $font; 

} 

?> 
2

您可以避免正則表達式的

$parsedUrl = parse_url($url); 
$queryString = $parsedUrl['query']; 
$parsedQueryString = parse_str($queryString); 
$fontName = array_shift(explode(':', $parsedQueryString['family'])); 
$idealFontName = urldecode($fontName); 
echo $idealFontName; 
+0

這不會用空格替代'+'。 – 2013-05-04 09:43:08

相關問題