簡體   English   中英

修改字符串內的4位數字並插入冒號

[英]Modify a 4 digit number inside of a string and inserting colon

我有一個字符串,我想修改所有4位數字並插入冒號。 示例:1320將成為13:20

$data = "The time is 1020 and the time is 1340 and 1550";

我想使用preg_match('/[0-9]{4}/', '????', $data);

但不確定如何在preg中再次傳遞相同的值?

一種方法是使用preg_replace代替並使用捕獲組在字邊界之間捕獲2次2位數(\\d{2})(\\d{2}) \\b

在替換中使用2個捕獲組使用$1:$2

$data = "The time is 1020 and the time is 1340 and 1550";
$data = preg_replace('/\b(\d{2})(\d{2})\b/', "$1:$2", $data);
echo $data;

結果:

The time is 10:20 and the time is 13:40 and 15:50

Php演示

您不需要使用捕獲組,您只需要尋找符合條件的4位數子串並在子串的中間定位零長度位置。

代碼:( 演示

$data = "The time is 1020 and the time is 1340 and 1550";    
echo preg_replace('~\b\d{2}\K(?=\d{2}\b)~', ':', $data);

輸出:

The time is 10:20 and the time is 13:40 and 15:50

\\b是一個單詞邊界,可確保您匹配序列中的第一個數字
\\d{2}匹配前兩位數字
\\K “重新啟動完整的字符串匹配” - 有效地忘記前兩位數字
(?=\\d{2}\\b)是兩位數后跟數字的預測。

preg_replace()用冒號替換零長度位置。


如果您想通過此替換來改進驗證,可以指定一些已知的字符范圍,如下所示:

echo preg_replace('~\b[0-2]\d\K(?=[0-5]\d\b)~', ':', $data);

當然,上述內容並非100%可靠,因為它可以匹配2900 驗證00002400之間的所有內容會變得更加毛茸茸:

echo preg_replace('~\b(?:(?:(?:[01]\d|2[0-3])\K(?=[0-5]\d\b))|(?:24\K(?=00\b)))~', ':', $data);

*注意,我不喜歡包含2400 ,但我已經閱讀了論據聲稱這是一個有效的時間。 這就是我包括它的原因。

如果你想省略2400作為有效值,那么它更易於管理( 0000 - 2359 ):

echo preg_replace('~\b(?:[01]\d|2[0-3])\K(?=[0-5]\d\b)~', ':', $data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM