-1

I have a load of labels which are camel case. Some examples are

whatData
whoData
deliveryDate
importantQuestions  

What I am trying to do is this. Any label which has the word Data needs to have this word removed. At the point of the capital letter, I need to provide a space. Finally, everything should be uppercase. I have done the removal of Data and the uppercase by doing this ($data->key is the label)

strtoupper(str_replace('Data', '', $data->key))

The part I am struggling with is adding the spaces between words. So basically the above words should end up like this

WHAT
WHO
DELIVERY DATE
IMPORTANT QUESTIONS

How can I factor in the last part of this?

Thanks

katie hudson
  • 2,765
  • 13
  • 50
  • 93

4 Answers4

4

It will add spaces before every capital letters. Try this:

$String = 'whatData';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
3

Problem

  • Your regex '~^[A-Z]~' will match only the first capital letter. Check out Meta Characters in the Pattern Syntax for more information.
  • Your replacement is a newline character '\n' and not a space.

Solution

Use preg_replace(). Try below code.

$string = "whatData";   
echo preg_replace('/(?<!\ )[A-Z]/', ' $0', $string);

Output

what Data
RJParikh
  • 4,096
  • 1
  • 19
  • 36
0

Try following:

$string = 'importantQuestions';
$string = strtoupper(ltrim(preg_replace('/[A-Z]/', ' $0', $string)));
echo $string;    

This will give you output as:

IMPORTANT QUESTIONS

Suyog
  • 2,472
  • 1
  • 14
  • 27
0

Try this:

preg_split:  split on camel case
array_map:   UPPER case all the element
implode:     Implode the array
str_replace: Replace the `DATE` with empty
trim:        trim the white spaces.

Do this simple things:

echo trim(str_replace("DATE", "", implode(" ", array_map("strtoupper", preg_split('/(?=[A-Z])/', 'deliveryDate', -1, PREG_SPLIT_NO_EMPTY))))); // DELIVERY

This is result exactly what you want.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42