Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uppercase the first character of each word in a string except 'and', 'to', etc

Tags:

php

How can I make upper-case the first character of each word in a string accept a couple of words which I don't want to transform them, like - and, to, etc?

For instance, I want this - ucwords('art and design') to output the string below,

'Art and Design'

is it possible to be like - strip_tags($text, '<p><a>') which we allow

and in the string?

or I should use something else? please advise!

thanks.

like image 657
Run Avatar asked Jan 02 '11 21:01

Run


2 Answers

You will have to use ucfirst and loop through every word, checking e.g. an array of exceptions for each one.

Something like the following:

$exclude = array('and', 'not');
$words = explode(' ', $string);
foreach($words as $key => $word) {
    if(in_array($word, $exclude)) {
        continue;
    }
    $words[$key] = ucfirst($word);
}
$newString = implode(' ', $words);
like image 80
fresskoma Avatar answered Oct 07 '22 05:10

fresskoma


None of these are really UTF8 friendly, so here's one that works flawlessly (so far)

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI"))
{
    /*
     * Exceptions in lower case are words you don't want converted
     * Exceptions all in upper case are any words you don't want converted to title case
     *   but should be converted to upper case, e.g.:
     *   king henry viii or king henry Viii should be King Henry VIII
     */
    $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
    foreach ($delimiters as $dlnr => $delimiter) {
        $words = explode($delimiter, $string);
        $newwords = array();
        foreach ($words as $wordnr => $word) {
            if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                // check exceptions list for any words that should be in upper case
                $word = mb_strtoupper($word, "UTF-8");
            } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                // check exceptions list for any words that should be in upper case
                $word = mb_strtolower($word, "UTF-8");
            } elseif (!in_array($word, $exceptions)) {
                // convert to uppercase (non-utf8 only)
                $word = ucfirst($word);
            }
            array_push($newwords, $word);
        }
        $string = join($delimiter, $newwords);
   }//foreach
   return $string;
}

Usage:

$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos' 
like image 38
Antonio Max Avatar answered Oct 07 '22 04:10

Antonio Max