php check a character on multiple lines of a string

799 Views Asked by At

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?

2

There are 2 best solutions below

0
On

strtr() will work to replace things:

Code: (Demo)

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

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

Output:

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

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 a double-space-dot.


Or 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

Or str_replace():

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

This adds an extra space before each dot, then "cleans up" by converting any double-spaces to single-spaces.

1
On

You can use preg_replace:

$output = preg_replace('/(\d+)([.\s]*)/m','$1 . ',$input);

Live demo