Add space to each letter in UPPERCASE

Asked

Viewed 739 times

4

How to make space using PHP when you start a capitalized word, for example, a string oiEusouMuitoLegal result in oi Eusou Muito Legal.

3 answers

9


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 that you do not add a space before a capital letter that already has a space before it.

Fonte

  • 1

    When will we have a regular expression to get a fresh cup of coffee in the morning? ;) +1

  • It’s just an untested hunch, but I think the regex ([^^ ])([A-Z]), with replace for $1 $2 also works.

  • 1

    @Zuul, let me know I need it!

5

You already have an answer that is undoubtedly the way forward, 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 in Ideone.


Code deals with the problem in question and illustrates the complexity of working a string without using regular expressions for operations based on a repetitive pattern.

1

echo preg_replace('/\B[A-Z]/', ' $0', "Olá oiEusouMuitoLegal! Tem Dias...");
//Olá oi Eusou Muito Legal! Tem Dias...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.