我想从“MAU120”中获取字符串“MAU”和“120”
来自“MAUL345”的和“MAUL”和“345”。
“MAUW”和“MAUW23”中的“23”
请在PHP中建议一系列代码。
答案 0 :(得分:5)
$matches = array();
if ( preg_match('/^([A-Z]+)([0-9]+)$/i', 'MAUL345', $matches) ) {
echo $matches[1]; // MAUL
echo $matches[2]; // 345
}
如果您需要MAU
,则可以执行以下操作:
/^(MAU[A-Z]*)([0-9]+)$/i
最后删除i
修饰符会使正则表达式区分大小写。
答案 1 :(得分:3)
试试这个正则表达式:
/(\D*)(\d*)/
PHP代码:
$matches = array();
var_dump( preg_match('/(\D*)(\d*)/', 'MAUL345', $matches) );
var_dump( $matches );
答案 2 :(得分:1)
从字面上看你的例子:
<?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\n\$num = %d\n\n", $str, $num);
}
?>
产地:
$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