2013-12-09 50 views
-1

小數插入零:使用前導零(0.4),P值小於1被設置沒有前導零(P = 0.05)PHP-正則表達式之前十進制

<?php 
    // Leading zero for decimals 
    $match=' 
    .5 
    p=.5 
    a= 67 
    687.689 
    .90 the decimal digit is 
    .56 '; 
    if (preg_match('/([a-zA-Z\s]+)?(?<!p=)(?<!\d)(\.(\d{1,}))/',$match)) 
    { 
     $replacement = '$1&nbsp;0$2'; 
     $replac = preg_replace('/([a-z A-Z\s]+)?(?<!p=)(?<!\d)(\.(\d{1,}))/', $replacement, $match); 
     echo $replac; 
    } 
    else 
     echo $match; 
?> 

輸入:

.5 
p=.5 
a=.67 
687.689 
.90 
the decimal digit is .56 

輸出:

0.5 p=.5 a= 0.67 687.689 0.90 the decimal digit is 0.56 

輸出是正確的,但如果我在附近p = .5輸入插入空間,輸出變成這樣:

0.5 p = 0.5 a= 0.67 687.689 0.90 the decimal digit is 0.56 

零不應對於p添加= 0.5

我該如何解決這個問題?

回答

0

容易,改變計數這樣的小數:

/([^p]\s+[=]+\s+)(\.\d{1,})/ 

編輯: 現在很清楚你想要的,這個新的字符串藉此輸入什麼:

a = .1 p = .5 

,併爲您提供:

a = 0.1 p = .5 
+0

'{2}'那是什麼意思? –

+1

@Matteo在這裏沒有問題,如果我給出這樣的輸入p = .5我的輸出變成p = 0.5這不是預期的輸入。輸出應該是p = .5 – user3064914

+0

@ ling.s意味着至少2,當前正則表達式檢查至少1({1,})並且將始終匹配.5 – Matteo

0

我終於找到了我的問題的答案。它可能不是一個更好的,但它會給出預期的結果。

if (preg_match('/([a-zA-Z\s]+)?(?<!p\s=\s)(?<!p=\s)(?<!p\s=)(?<!p=)(?<!\d)(\.(\d{1,}))/', $match)) 
{ 
... 
} 

輸入:

p = .5 a = .5 

輸出:

p = .5 a = 0.5 
+0

現在很清楚,用更短的正則表達式更新了我的答案 – Matteo