2011-05-19 61 views
0

如何每4個字符後面加一個-添加符號與PHP

例子:

498c665baf79ad6e - >498c-665b-af79-ad6e

+0

你有字符串嗎?或數組?你有什麼想要添加破折號? – Nanne 2011-05-19 10:49:14

+0

你的輸入如何,你能舉例 – AjayR 2011-05-19 10:52:29

+0

我使用變量'md5()' – Cheerio 2011-05-19 11:56:57

回答

11
echo implode('-', str_split('498c665baf79ad6e', 4)); 
1
<?php 

$source = "..."; 

$hypenated = array(); 

for ($i = 0; $i < strlen($source)/4; $i++) { 
    $hypenated[] = substr($source, $i*4, 4); 
} 

$hypenated = implode('-', $hypenated); 
+2

我認爲有* typo *,這個必須是'$ hypenated =「 - 」',我對嗎? – diEcho 2011-05-19 10:51:29

+0

你忘了在substr的末尾添加連字符;)'$ hyphenated。= substr(...)。 ' - ';'在'for'循環之後:'$ hyphenated = substr($ hyphenated,0,-1);' – 2011-05-19 10:52:36

+0

@diEcho,oops,謝謝,修正。 – erenon 2011-05-19 10:53:15

1
$s = '498c665baf79ad6e'; 
echo preg_replace ('/(.{4})(?=.)/', '\1-', $s); 
1

或者:

<?php 
echo rtrim(chunk_split('498c665baf79ad6e', 4, '-'), '-');