Add space to each letter in UPPERCASE

4

How to make room using PHP when starting a capitalized word, for example, string oiEusouMuitoLegal results in oi Eusou Muito Legal .

    
asked by anonymous 01.01.2015 / 00:33

3 answers

8

To do this you can use the following regex , /(?<!\ )[A-Z]/ .

   
$str = "oiEusouMuitoLegal";
echo preg_replace('/(?<!\ )[A-Z]/', ' $0', $str);
// oi Eusou Muito Legal

Ideone

The (?<!\ ) excerpt is a statement that will make sure you do not add a space before an uppercase letter that already has a space before it.

Fonte

    
01.01.2015 / 01:08
5

You already have an answer that undoubtedly is the way forward, it is an example for those who do not want to use regular expressions:

$texto = "oiEusouMuitoLegal";

$letras = preg_split('//', $texto, -1, PREG_SPLIT_NO_EMPTY);

foreach ($letras as $letra) {

    if (ctype_upper($letra)) {
        $texto = str_replace($letra, " $letra", $texto);
    }
}

echo $texto;  // Saída: oi Eusou Muito Legal

Example on Ideone .

The code handles the problem in question and illustrates the complexity of working a string without using regular expressions for operations based on a repetitive pattern.     

01.01.2015 / 01:32
1
echo preg_replace('/\B[A-Z]/', ' $0', "Olá oiEusouMuitoLegal! Tem Dias...");
//Olá oi Eusou Muito Legal! Tem Dias...
    
19.03.2015 / 19:09