开发者

PHP - preg_match - assign arbitrary value to a matched element

assuming we have this regex:

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

now, whenever the regex match for ex. one of the three xbox methods (xbox|xbox360|360), the $matches, should return just XBOX

is this possible continuing to work in the preg_match() context or i should use som开发者_如何学Pythone other method?

thank's in advance.

EDITED:

im actually doing it like this:

$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';
}

i'm wondering if there is another way!


your current code looks ok to me, if you want it a bit fancier, you can try named subpatterns

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

or preg_replac'ing things before matching:

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

on big inputs i guess your method would be the fastest. A minor improvement would be to replace in_array with a hash-based lookup:

$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';
}

named subpatterns: see http://www.php.net/manual/en/regexp.reference.subpatterns.php and http://php.net/manual/en/function.preg-match-all.php, example 3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜