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 some 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!

Answers


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


Need Your Help

How to translate dynamic form choices

python django python-2.7 django-i18n

I am using the same form and changing the choices.

How do I call Linux syscall from kernel space?

linux-kernel syscall

I'm porting linux kernel module written for Linux 2.4 to work with Linux 2.6.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.