How to use words in brackets in a sentence
I am using the following code to capitalize each word in a sentence, but I cannot use words with parentheses attached.
PHP code:
<?php
$str = "[this is the {command line (interface ";
$output = ucwords(strtolower($str));
echo $output;
Output:
[this Is The {command Line (interface
But my expected output should be:
[this Is The {command Line (interface
How can I handle words with parentheses? There may be multiple parentheses.
For example:
[{this is the ({command line ({(interface
I want to find a general solution / function in PHP.
source to share
$output = ucwords($str, ' [{(');
echo $output;
// output ->
// [This Is The {Command Line (Interface
Update: general solution. Here "bracket" is any non-letter character. Any letter following the "parenthesis" is converted to uppercase.
$string = "test is the {COMMAND line -STRET (interface 5more 9words #here";
$strlowercase = strtolower($string);
$result = preg_replace_callback('~(^|[^a-zA-Z])([a-z])~', function($matches)
{
return $matches[1] . ucfirst($matches[2]);
}, $strlowercase);
var_dump($result);
// string(62) "Test Is The {Command Line -Stret (Interface 5More 9Words #Here"
Live demo
source to share
This is another solution, you can add more delimiters to the array for each loop if you want to handle more characters.
function ucname($string) {
$string =ucwords(strtolower($string));
foreach (array('-', '\'') as $delimiter) {
if (strpos($string, $delimiter)!==false) {
$string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
}
}
return $string;
}
?>
<?php
//TEST
$names =array(
'JEAN-LUC PICARD',
'MILES O\'BRIEN',
'WILLIAM RIKER',
'geordi la forge',
'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n<br />"); }
//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
source to share