How to make room using PHP when starting a capitalized word, for example, string oiEusouMuitoLegal
results in oi Eusou Muito Legal
.
How to make room using PHP when starting a capitalized word, for example, string oiEusouMuitoLegal
results in oi Eusou Muito Legal
.
To do this you can use the following regex , /(?<!\ )[A-Z]/
.
$str = "oiEusouMuitoLegal";
echo preg_replace('/(?<!\ )[A-Z]/', ' $0', $str);
// oi Eusou Muito Legal
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.
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.
echo preg_replace('/\B[A-Z]/', ' $0', "Olá oiEusouMuitoLegal! Tem Dias...");
//Olá oi Eusou Muito Legal! Tem Dias...