PHP Ucwords with or and special characters

此生再无相见时 提交于 2020-01-06 04:13:05

问题


Here is what I'm doing.

I have a couple of strings that is uppercase

†HELLO THERE
DAY OR NIGHT

So to convert them, I'm using the following code:

ucwords(strtolower($string));

Here is the end result:

†hello There
Day Or Night

How can I ignore the or any special characters so it the words can show

†Hello There

and how can I keep words like or all lowercase.


回答1:


Try:

print preg_replace_callback('#([a-zA-ZÄÜÖäüö0-9]+)#',function($a){
   return ucfirst(strtolower($a[0]));
 },
 '†hello THERE'
);

[a-zA-ZÄÜÖäüö0-9]+ find a word that only has this chars

You can also use this instead [\w]+ see: http://www.regular-expressions.info/wordboundaries.html

preg_replace_callback call a function on the found result

function($a){} do something with the result, here ucfirst(strtolower())




回答2:


    $lowerString = strtolower($string);
    $stringArray = explode($lowerString, ' ');
    foreach ($stringArray as $key => $singleString) {
        $i = 0; 
        $formatedString = '';
        $upcased = false;
        for ($i; $i < strlen($singleString); $i++) {
            $ascNum = chr($singleString[$i]);
            $word = $singleString[$i];
            if (!$upcased) {
              if (($ascNum >= 65 && $ascNum <= 90) || ($ascNum >= 97 && $ascNum <= 122) ) {
                $word = ucwords($word);
                $upcased = true;
              }
            }
            $formatedString .= $word;  
        }
        $stringArray[$key] = $formatedString;
    }
    $result = implode(' ',$stringArray);

maybe a little complicated, but a clean idea.




回答3:


ucwords(strtolower("†HELLO THERE"),"† "); the second parameter of ucwords is an optional delimiter. So by including both dagger and space, ucwords will work for the examples provided.

for your second question, see here




回答4:


Assuming words are separated by a space:

<?php
function custom_ucfirst($s)
{
    $s = strtolower($s);

    $e = (strpos($s, ' ') !== false ? explode(' ', $s) : array($s));

    $keep_all_lowercase = array('or','and','but');

    foreach($e as $k=>$v)
    {
        if(!in_array($v, $keep_all_lowercase))
        {
            $str_split = str_split($v);

            foreach($str_split as $k2=>$v2)
            {
                if(in_array($v2, range('a','z')))
                {
                    $str_split[$k2] = strtoupper($v2);
                    break;
                }
            }

            $e[$k] = implode('', $str_split);
        }
    }

    return implode(' ', $e);
}

echo custom_ucfirst('†HELLO THERE .cloud. or sky what a nice an*d ()good day.');

// †Hello There .Cloud. or Sky What A Nice An*d ()Good Day.


来源:https://stackoverflow.com/questions/38529663/php-ucwords-with-or-and-special-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!