1

Like for example :

$sampe = 'UNITED STATES OF AMERICA';
$sampc = ucwords(strtolower($sampe));

result : United States Of America

I want like this

result : United States of America

how to exempt "of"?

kim de castro
  • 299
  • 6
  • 19

5 Answers5

0

You can try this -

$sample = 'UNITED STATES OF AMERICA';

function convert_str($str)
{
    $except = array('of', 'in', 'is'); // Words you dont want to convert
    $str= strtolower($str); // apply strtolower to all
    return (in_array($str, $except)) ? $str : ucwords($str); // apply ucwords conditionally
}

$temp = explode(' ', $sample); // explode by space
$new_temp = array_map('convert_str', $temp); // apply the function to every element

echo implode(' ', $new_temp); // implode again

But it is for the text you provided. It might need to be changed accordingly.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

Try the below function

    $country = 'UNITED STATES OF AMERICA';
    function countryToLowerCase( $country )
    {
        $except = array('of','in');
        $parts = explode(' ', $country);
        $country = null;
        foreach ($parts as $part) {
            if(!in_array( $part, $except))
            {
                    $country .= ucfirst($part) .' ';
                    continue;
            }
            $country .= $part .' ';
        }
        return $country;
    }
    echo countryToLowerCase( strtolower($country));//United States of America 
Basheer Kharoti
  • 4,202
  • 5
  • 24
  • 50
0

I would use an array of list that you would want to change it back to lowercase, like the following

$filterback = array("of", "in", "is");

$str = 'UNITED STATES OF AMERICA';
$upper = ucwords(strtolower($str));
$filtered = str_ireplace($filterback, $filterback, $upper);
echo $filtered; // United States of America
Andrew
  • 2,810
  • 4
  • 18
  • 32
-1

If you save UNITED , STATES, and AMERICA in three different variables and apply the above code individually to these three strings and then save in a single variable. Then you should be able to get the result you want. Otherwise the php is not intelligent enough to see that the country name should start with a capital letter.

  • 1
    You are posting two answers for a single question. Why not a single answer with proper code example and explanation? – Sougata Bose Dec 08 '15 at 09:18
-1

You have to truncat the first variable into three variables. The first variable should contain "United States" , The second variable should contain "of" and the third variable should contain "America" . Apply strtolower function on the first and the third variable . Then add the three variables into one variable to get the required result.

Easy . Isn't it!.