2017-08-30 77 views
0

我有在未來一個字符串的多行檢查字符是一個多行字符串,根據輸入的格式稍有不同PHP上的繩子

 1. Qatar 
2. Qatar 
3 . Cathay 
4. Qatar 
2 . British 
3. Qantas

我想要的輸出字符串具有相同格式的所有行:

 1 . Qatar 
2 . Qatar 
3 . Cathay 
4 . Qatar 
2 . British 
3 . Qantas

我可以使它檢查使用

$fullstop = substr("$input", 2); //isolate character 2 



if (strpos($fullstop, '.') !== false) { //check is the character in pos 2 is a . 
$output = str_replace("."," .",$fullstop); //replace the full stop with space fullstop 
} 

釷第一線對於第一行來說工作正常,但是我希望代碼對所有代碼行都做同樣的事情。

任何想法?

+0

你的琴絃之上都有第一個數字(例如 「1 Quatar」)前的空白(空格)字符。這是一個錯字嗎? – BeetleJuice

+1

只是用'space-dot'替換'space-dot's和'dot',對吧? – mickmackusa

回答

0

strtr()將致力於替代的東西:

代碼:(Demo

$string=' 
1. Qatar 
2. Qatar 
3 . Cathay 
4. Qatar 
2 . British 
3. Qantas'; 

var_export(strtr($string,[' .'=>' .','.'=>' .'])); 

輸出:

' 
1 . Qatar 
2 . Qatar 
3 . Cathay 
4 . Qatar 
2 . British 
3 . Qantas' 

strtr()是這個任務的一個偉大的功能,因爲它第一次取代最長匹配,並且一旦子字符串被替換,它將不會在相同的調用中被再次替換。這就是爲什麼space-dot永遠不會成爲double-space-dot


或者preg_replace()

var_export(preg_replace('/\d+\K\./',' .',$string)); // digit then dot 
//       ^^--- restart fullstring match (no capture group needed) 

var_export(preg_replace('/(?<=\d)\./',' .',$string)); // dot preceded by a digit 

var_export(preg_replace('/(?<!)\./',' .',$string)); // dot not preceded by a space 

或者str_replace()

var_export(str_replace(['.',' '],[' .',' '],$string)); 

這每一個點之前增加了一個額外的空間,然後通過將任何雙空格單幅 「清理」空間。