note 84920 modified in function.ucwords by yannick
| From: | yannick@php.net | Date: | Thu, 07 Aug 2008 13:49:02 +0000 |
| Subject: | note 84920 modified in function.ucwords by yannick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-143270@lists.php.net to get a copy of this message | ||
I modified Q1712's code (below) to use regular expressions
instead of characters to properly capitalize words that fall
directly after an unwanted character. See his post for details.
This version allows me to use it around html elements, etc.
<?php
function my_ucwords($string){
$invalid_characters = array('"',
'\(',
'\[',
'\/',
'<.*?>',
'<\/.*?>');
foreach($invalid_characters as $regex){
$string = preg_replace('/('.$regex.')/','$1 ',$string);
}
$string=ucwords($string);
foreach($invalid_characters as $regex){
$string = preg_replace('/('.$regex.') /','$1',$string);
}
return $string;
}
?>
Moreover, to get a proper title case, i combine it with this function:
This Function is obtained from:
http://codesnippets.joyent.com/posts/show/716
<?php
function title_case($title) {
$smallwordsarray = array(
'of','a','the','and','an','or','nor','but','is','if','then',
'else','when',
'at','from','by','on','off','for','in','out',
'over','to','into','with'
);
$words = explode(' ', $title);
foreach ($words as $key => $word)
{
if ($key == 0 or !in_array($word, $smallwordsarray))
$words[$key] = $this->my_ucwords(strtolower($word));
}
$newtitle = implode(' ', $words);
return $newtitle;
}
?>
Hope you find it useful.
--was--
I modified Q1712's code (below) to use regular expressions
instead of characters to properly capitalize words that fall
directly after an unwanted character. See his post for details.
This version allows me to use it around html elements, etc.
function my_ucwords($string){
$invalid_characters = array('"',
'\(',
'\[',
'\/',
'<.*?>',
'<\/.*?>');
foreach($invalid_characters as $regex){
$string = preg_replace('/('.$regex.')/','$1 ',$string);
}
$string=ucwords($string);
foreach($invalid_characters as $regex){
$string = preg_replace('/('.$regex.') /','$1',$string);
}
return $string;
}
Moreover, to get a proper title case, i combine it with this function:
//This Function is obtained from:
http://codesnippets.joyent.com/posts/show/716
function title_case($title) {
$smallwordsarray = array(
'of','a','the','and','an','or','nor','but','is','if','then',
'else','when',
'at','from','by','on','off','for','in','out',
'over','to','into','with'
);
$words = explode(' ', $title);
foreach ($words as $key => $word)
{
if ($key == 0 or !in_array($word, $smallwordsarray))
$words[$key] = $this->my_ucwords(strtolower($word));
}
$newtitle = implode(' ', $words);
return $newtitle;
}
Hope you find it useful.
http://php.net/manual/en/function.ucwords.php