2010-12-01 67 views
1

假設我們有這個表達式:PHP - 的preg_match - 分配任意值匹配的元素

preg_match('/\b(xbox|xbox360|360|pc|ps3|wii)\b/i' , $string, $matches); 

現在,每當正則表達式匹配前。三種方法的Xbox一個(的Xbox | XBOX360 | 360),在$matches,應該僅返回XBOX

這可能繼續在preg_match()上下文中工作或我應該用一些其他的方法?

提前致謝。

編輯:

我其實做這樣的:

$x = array('xbox360','xbox','360'); 
if(preg_match('/\b(xbox360|xbox|360|pc|ps3)\b/i', $s, $m)) { 
    $t = $m[0]; 
} 
if (in_array($t,$x)) { 
    $t = 'XBOX'; 
} 

我不知道是否有另一種方式!

回答

2

您當前的代碼看起來不錯給我,如果你想讓它有點愛好者,你可以嘗試匹配之前命名的子模式

preg_match('/\b((?P<XBOX>xbox|xbox360|360)|pc|ps3|wii)\b/i' , $string, $matches); 
$t = isset($matches['XBOX']) ? 'XBOX' : $matches[0]; 

或preg_replac'ing事情:

$string = preg_replace('~\b(xbox|xbox360|360)\b~', 'XBOX', $string); 
preg_match('/\b(XBOX|pc|ps3|wii)\b/i' , $string, $matches); 

上大投入我想你的方法會是最快的。很小的改善將是一個基於散列的查找替換in_array

$x = array('xbox360' => 1,'xbox' => 1,'360' => 1); 
if(preg_match('/\b(xbox360|xbox|360|pc|ps3)\b/i', $s, $m)) { 
    $t = $m[0]; 
} 
if (isset($x[$t]) { 
    $t = 'XBOX'; 
} 

命名的子模式:見http://www.php.net/manual/en/regexp.reference.subpatterns.phphttp://php.net/manual/en/function.preg-match-all.php,例如3

+0

TNXŸ非常多,你的正則表達式的石頭! ;)你能否解釋(?x xbox | xbox360 | 360)的一部分? – 2010-12-01 19:10:16