2011-10-12 48 views
2

我想從「MAU120」我想從字符串獲得子第一個數字出現

和「MAUL」和「345」,從「MAUL345」獲得字符串「MAU」和「120」之前。

「MAUW」 和 「23」,從 「MAUW23」

請提出一系列的代碼需要PHP。

+0

您可以使用正則表達式。 – ComFreek

+2

我們會有沒有字母的數字,或沒有數字的字母? –

+0

它總是以MAU開頭,並以您的例子中的數字結尾?如果你可以指定一個通用模式而不是隨機的例子,這會更有幫助。 – Herbert

回答

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修改將使正則表達式區分大小寫。

+0

也匹配'mAuL345'和'bob2'。 – Herbert

+2

OP從來沒有說過'MAU'是一個要求,也不是案例。我編輯了我的答案,以顯示一種方法來要求'MAU'並添加了關於大小寫修飾符的信息。 – webbiedave

+0

對不起@webbie。我並不是在批評你的方法。我只是指出了OP未通過示例指定的一些匹配。問題在於OP沒有對所希望的模式做任何說明。儘管如此,這是一個好得多的答案。 +1 :-) – Herbert

3

試試這個正則表達式:

/(\D*)(\d*)/ 

PHP代碼:

$matches = array(); 

var_dump(preg_match('/(\D*)(\d*)/', 'MAUL345', $matches)); 
var_dump($matches); 
+0

看起來很危險。 。 。 「?@#!123」現在解析。 。 。 –

+0

適合我的工作,請在這裏嘗試:http://phpcodepad.com/ – ComFreek

+0

'?@#!123'將被解析爲'?@#!'和'123'。這可能會引入能夠正確分析OP所不希望的字符。因此,看起來很危險。 –

1

從你的例子從字面上看:

<?php 
$tests = array('MAU120', 'MAUL345', 'MAUW23', 'bob2', '[email protected]#!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 = [email protected]#!123 
$str = 
$num = 0 

$test = In the MAUX123 middle. 
$str = MAUX 
$num = 123 
相關問題