Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP capitalize after dash [duplicate]

Tags:

php

$q = 'durham-region';

$q = ucfirst($q);

$q = 'Durham-region';

How would I capitalize the letter after the dash (Durham-Region)? Would I have to split the two and capitalize?

like image 957
mrlayance Avatar asked Apr 05 '11 01:04

mrlayance


4 Answers

Updated Solution

As of PHP 5.5, the e modifier for preg_replace has been deprecated. The best option now is to use one of the suggestions that does not use this, such as:

$q = preg_replace_callback('/(\w+)/g', create_function('$m','return ucfirst($m[1]);'), $q)

or

$q = implode('-', array_map('ucfirst', explode('-', $q)));

Original Answer

You could use preg_replace using the e modifier this way:

$test = "durham-region";
$test = preg_replace("/(\w+)/e","ucfirst('\\1')", $test);
echo $test;
// Durham-Region
like image 180
Kelly Avatar answered Oct 30 '22 16:10

Kelly


Thanks to the delimiter parameter of ucwords, since PHP 5.4.32 and 5.5.16, it is as simple as this:

$string = ucwords($string, "-");
like image 13
Alexander Jank Avatar answered Oct 30 '22 18:10

Alexander Jank


A one-liner that doesn't envolve using the e PCRE modifier:

$str = implode('-', array_map('ucfirst', explode('-', $str)));
like image 9
Alix Axel Avatar answered Oct 30 '22 18:10

Alix Axel


another oneliner:

str_replace(' ','',ucwords(str_replace('-',' ',$action)))
like image 1
Flion Avatar answered Oct 30 '22 16:10

Flion