Jump to content

Titlecase function not working


bulrush

Recommended Posts

I thought this was pretty straight forward, but it is not working. Titlecase is supposed to capitalize the first letter of every with except for certain words in $smallarr. Instead, it capitalizes every word. What's wrong here?

//====================================================
function crTitlecase($s)
/* Capitalize every word in a sentence except certain small words.
*/ 
{
//Keep $smallarr in alpha order!
//Do not capitalize these words.
$smallarr=array('a','above','and','an','at','by','for','if');
$smallarr=array($smallarr,'into','is','it','of','off');
$smallarr=array($smallarr,'on','or','over','the','to');
$smallarr=array($smallarr,'with','without');
//$smallarr=($smallarr,);

$t=strtolower($s); //First change all ltrs to lowercase.
$words = explode(' ', $t);
foreach ($words as $mykey => $word) 
{ 
//if ((!$mykey) or (!in_array($word, $smallarr)) ) 
if ( (!in_array($word, $smallarr)) ) 
	{
	$s='mykey='.$mykey.', word='.$words[$mykey];
	crDebug($s);
	$words[$mykey] = ucwords($word); 
	}
}
$newtitle = implode(' ', $words);
return $newtitle;
}

 

Link to comment
https://forums.phpfreaks.com/topic/211054-titlecase-function-not-working/
Share on other sites

I haven't looked through it all, but first off, you're building a four dimensional array that won't work as needed in the in_array().  Try replacing your multiple array definitions with:

 

$smallarr = array('a','above','and','an','at','by','for','if','into','is','it','of','off','on','or','over','the','to','with','without');

 

 

Many ways.  Here's one:

 

I haven't looked through it all, but first off, you're building a four dimensional array that won't work as needed in the in_array().  Try replacing your multiple array definitions with:

 

$smallarr = array(
   'a','above','and','an','at','by',
   'for','if','into','is','it','of',
   'off','on','or','over','the','to',
   'with','without'
);

Just for fun, this will do it and also make sure the first word in the string is capitalized:

 

function crTitlecase($s) {

$smallarr = array(
	'a','above','and','an','at','by',
	'for','if','into','is','it','of',
	'off','on','or','over','the','to',
	'with','without'
);

foreach(explode(' ', ucfirst(strtolower($s))) as $word) {
	if(!in_array($word, $smallarr)) {
		$words[] = ucfirst($word);
	} else {
		$words[] = $word;
	}
}
return implode(' ', $words);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.