I've got a string coming in which is a multiple line string, depending on the input the format is slightly different
1. Qatar 2. Qatar 3 . Cathay 4. Qatar 2 . British 3. Qantas
I want the output string to have the same format for all lines:
1 . Qatar 2 . Qatar 3 . Cathay 4 . Qatar 2 . British 3 . Qantas
I can make it check the first line using
$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
}
This works fine for the first line, however I want the code to do the same for all the lines of code.
Any ideas?
strtr()
will work to replace things:Code: (Demo)
Output:
strtr() is a great function for this task because it replaces longest matches first, and once a substring is replaced, it will not be replaced again in the same call. This behavior is why a
space-dot
never becomes adouble-space-dot
.Or
preg_replace()
:Or
str_replace()
:This adds an extra space before each dot, then "cleans up" by converting any double-spaces to single-spaces.