2016-07-28 71 views
0

問題:匹配3倍最後的數字字符串中的正則表達式與

刻意突出使用正則表達式字符串中的最後3個數字。

代碼:

<?php 
    show_source('regex.php'); 

    $string = " 
     780155OVERF I000000 
     TRANFER DOMESTIC 
     000114 
     STHLM SE AB 
    "; 
?> 
<!DOCTYPE html> 
<html> 
    <head> 
     <title>Regex to match last 3 numbers</title> 
     <meta charset="utf-8"> 
    </head> 
    <body> 
     <?php 
      echo nl2br(str_replace('/\d{3}(?=[^\d]+$)/g', '<span style="background-color:red;">$1</span>', $string)); 
     ?> 
    </body> 
</html> 

期望的結果:

數字114應該有紅色的背景顏色。

+0

現在怎麼顯示? –

+2

'str_replace'不處理REGEX使用'preg_replace' – JustOnUnderMillions

+0

它運作良好https://www.regex101.com/r/yR4uX6/1 –

回答

1

用途:

print nl2br(
     preg_replace('/\d{3}(?=[^\d]+$)/s', 
        '<span style="background-color:red;">$0</span>', 
        $string) 
      ); 
2

主要錯誤:str_replace不能用正則表達式工作。使用preg_replace

$string = " 
    780155OVERF I000000 
    TRANFER DOMESTIC 
    000114 
    STHLM SE AB 
"; 

// use `m` modifier as you have multiline string 
// `g` modifier is not supported by preg_replace 
echo preg_replace("/\d{3}(?=[^\d]+)$/m", '<span>$0</span>', $string);