I want to get the string "MAU" and "120" from "MAU120"
and "MAUL" and "345" from "MAUL345".
"MAUW" and "23" from "MAUW23"
Please suggest the series of code require in PHP.
$matches = array();
if ( preg_match('/^([A-Z]+)([0-9]+)$/i', 'MAUL345', $matches) ) {
echo $matches[1]; // MAUL
echo $matches[2]; // 345
}
If you require the MAU
you can do:
/^(MAU[A-Z]*)([0-9]+)$/i
Removing i
modifier at the end will make the regex case-sensitive.
Try this regular expression:
/(\D*)(\d*)/
PHP code:
$matches = array();
var_dump( preg_match('/(\D*)(\d*)/', 'MAUL345', $matches) );
var_dump( $matches );
Taken literally from your examples:
<?php
$tests = array('MAU120', 'MAUL345', 'MAUW23', 'bob2', '?@#!123', 'In the MAUX123 middle.');
header('Content-type: text/plain');
foreach($tests as $test)
{
preg_match('/(MAU[A-Z]?)(\d+)/', $test, $matches);
$str = isset($matches[1]) ? $matches[1] : '';
$num = isset($matches[2]) ? $matches[2] : '';
printf("\$str = %s
\$num = %d
", $str, $num);
}
?>
Produces:
$test = MAU120
$str = MAU
$num = 120
$test = MAUL345
$str = MAUL
$num = 345
$test = MAUW23
$str = MAUW
$num = 23
$test = bob2
$str =
$num = 0
$test = ?@#!123
$str =
$num = 0
$test = In the MAUX123 middle.
$str = MAUX
$num = 123