Reputation: 10525
How can I convert to uppercase for the following example :
title-title-title
Result should be:
Title-Title-Title
I tried with ucwords but it converts like this: Title-title-title
I currently have this:
echo $title = ($this->session->userdata('head_title') != '' ? $this->session->userdata('head_title'):'Our Home Page');
Upvotes: 2
Views: 1334
Reputation: 1280
Edit #2
This isn't working for the new information added to op, as there is an answer this won't be updated to reflect that.
Edit #1
$var = "title-title-title";
$var = str_replace (" ", "_", ucwords (str_replace (" ", "_", $var));
Old, non-working
$var = "title-title-title";
$var = implode("-", ucwords (explode("-", $var)));
Upvotes: -1
Reputation: 15091
Not as swift as Ghost's but a touch more readable for beginners to see what's happening.
//break words on delimiter
$arr = explode("-", $string);
//capitalize first word only
$ord = array_map('ucfirst', $arr);
//rebuild the string
echo implode("-", $ord);
The array_map()
applies callback to the elements of the given array. Internally, it traverses through the elements in our word-filled array $arr
and applies the function ucfirst()
to each of them. Saves you couple of lines.
Upvotes: 1
Reputation: 41885
In this particular string example, you could explode the strings first, use that function ucfirst()
and apply to all exploded strings, then put them back together again:
$string = 'title-title-title';
$strings = implode('-', array_map('ucfirst', explode('-', $string)));
echo $strings;
Should be fairly straightforward on applying this:
$title = '';
if($this->session->userdata('head_title') != '') {
$raw_title = $this->session->userdata('head_title'); // title-title-title
$title = implode('-', array_map('ucfirst', explode('-', $raw_title)));
} else {
$title = 'Our Home Page';
}
echo $title;
Upvotes: 6
Reputation: 57
try the following:
$str='title-title-title';
$s='';
foreach(explode('-',$str) as $si){
$s.= ($s ? "-":"").ucfirst($si);
}
$s
should be Title-Title-Title
at this point
Upvotes: -2
Reputation: 46910
echo str_replace(" ","-",ucwords(str_replace("-"," ","title-title-title")));
Output:
Title-Title-Title
Upvotes: 4