Log in

View Full Version : ucwords, pregreplace, skip first



bluewalrus
04-27-2010, 03:44 PM
I have this code:


$title = trim($_POST['title']);
$case_changed = ucwords($title);
$case_changed = str_replace("Of", "of", $case_changed);
$case_changed = str_replace("And", "and", $case_changed);
$case_changed = str_replace("For", "for", $case_changed);
$case_changed = str_replace("From", "from", $case_changed);
//Multiple patterns and replacements for entities and greek words
$case_changed = preg_replace($patterns, $replacements, $case_changed);
echo $case_changed;


which is suppose to create Title Case for text entered. How can I run the str_replace on all words after the first because the first word should always be capitalized. I was thinking substr($case_changed, 0, $X) but the first word will never have the same amount of characters.

Thanks for any ideas. (I solved my second question about ucwords and pregreplace after posting and seeing the code some other place).

djr33
04-27-2010, 05:28 PM
This is all about ordering.
First, uppercase all words; second, lowercase the specific words you want to avoid; third, make the first word of the string uppercase:
$str[0] = strtoupper($str[0]);

Another way to go about this would be to explode everything into words and do this individually to each word, that way giving individual control for each word. But the way above works.

You can also setup an array to do the re-lowercasing.

bluewalrus
05-31-2010, 11:20 PM
I forgot about this one, I came up with this...



$title = trim($_POST['title']);
$case_changed = ucwords($title);
$case_changed = str_replace("Of ", "of ", $case_changed);
$case_changed = str_replace("The ", "the ", $case_changed);
$case_changed = str_replace("From", "from", $case_changed);
$title_length = strlen($case_changed);
$case_changed = strtoupper(substr($case_changed, 0, 1)) . substr($case_changed, 1, $title_length);


See anything wrong with it?

djr33
06-01-2010, 10:58 AM
That looks fine. The only problem is that str_replace isn't smart-- it doesn't know when it's a separate word. You have a space after 'of' and 'the' but not 'from'. Still, though, you can find it if it's the end of a word, like 'bathe' for 'the', etc.
The rest of the logic is fine, but if you find a way to replace 'whole words' that may be better. Regex could be the answer: the word must be bordered by spaces, punctuation or the ends of the string.
There also may be a PHP function for this, but I don't remember.... take a look around php.net.