views:

172

answers:

6

I have two types of strings, 'hello', 'helloThere'.

What I want is to change them so they read like: 'Hello', 'Hello There' depending on the case.

What would be a good way fo doing this?

Thanks

+3  A: 

Use the ucwords function:

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

This will not split up words that are slammed together - you will have to add spaces to the string as needed for this function to work.

Andrew Hare
he needs to add the space first with `helloThere`
+1  A: 

PHP has many string manipulation functions. ucfirst() would do it for you.

http://ca3.php.net/manual/en/function.ucfirst.php

Angelo R.
No, that function can not change CamelCase to Camel Case
JochenJung
+1  A: 

Use the ucwords function:

echo ucwords('hello world');
Sarfraz
+6  A: 

To convert CamelCase to different words:

preg_replace('/([^A-Z])([A-Z])/', "$1 $2", $string)

To uppercase all the words first letters:

ucwords()

So together:

ucwords(preg_replace('/([^A-Z])([A-Z])/', "$1 $2", $string))
JochenJung
A: 

you can use ucwords like everyone said... to add the space in helloThere you can do $with_space = preg_replace('/[A-Z]/'," $0",$string); then ucwords($with_space);

A: 

use ucwords

<?php
$foo = 'hello world';
$foo = ucwords($foo);             // Hello world

$bar = 'BONJOUR TOUT LE MONDE!';
$bar = ucwords($bar);             // HELLO WORLD
$bar = ucwords(strtolower($bar)); // Hello World
?>
taichimaro