PHP Doku:: Wandelt alle Zeichen eines Strings in Großbuchstaben um - function.strtoupper.html

Verlauf / Chronik / History: (7) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenstrtoupper

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<strtolower

strtr>>

strtoupper

(PHP 4, PHP 5)

strtoupperWandelt alle Zeichen eines Strings in Großbuchstaben um

Beschreibung

string strtoupper ( string $string )

Gibt string zurück, in dem alle Buchstaben in Großbuchstaben umgewandelt wurden.

Beachten Sie, dass die Erkennung von 'Buchstaben' vom Wert locale abhängig ist. Ist z. B. die Voreinstellung für locale "C", werden Sonderzeichen wie Umlaute (ä, ö, ü) nicht umgewandelt.

Parameter-Liste

string

Die Eingabezeichenkette.

Rückgabewerte

Gibt die Zeichenkette in Großbuchstaben zurück.

Beispiele

Beispiel #1 strtoupper()-Beispiel

<?php
$str 
"Mary Hat Ein Kleines Lamm, und Sie LIEBT Es So.";
$str strtoupper($str);
echo 
$str// Gibt aus: MARY HAT EIN KLEINES LAMM, UND SIE LIEBT ES SO.
?>

Anmerkungen

Hinweis: Diese Funktion ist binary safe.

Siehe auch

  • strtolower() - Setzt einen String in Kleinbuchstaben um
  • ucfirst() - Verwandelt das erste Zeichen eines Strings in einen Großbuchstaben
  • ucwords() - Wandelt jeden ersten Buchstaben eines Wortes innerhalb eines Strings in einen Großbuchstaben
  • mb_strtoupper() - Make a string uppercase


30 BenutzerBeiträge:
- Beiträge aktualisieren...
smieat
2.05.2010 1:39
perfect solutions for turkish utf-8 (including i I conversations):

<?php
function strtolowertr($metin){
    return
mb_convert_case(str_replace('I','ı',$metin), MB_CASE_LOWER, "UTF-8");
}

function
strtouppertr($metin){
    return
mb_convert_case(str_replace('i','İ',$metin), MB_CASE_UPPER, "UTF-8");
}

function
ucwordstr($metin) {
    return
ltrim(mb_convert_case(str_replace(array(' I',' ı', ' İ', ' i'),array(' I',' I',' İ',' İ'),' '.$metin), MB_CASE_TITLE, "UTF-8"));
}

function
ucfirsttr($metin) {
   
$metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),substr($metin,1));
return
$metin[0].$metin[1];
}
?>
php at emanaton dot com
6.11.2009 17:38
I liked jesdisciple's approach to a camel case function, but needed something a little more high powered, so here is my stab at this need:

<?php
/**
 * Convert a string to camel case, optionally capitalizing the first char and optionally setting which characters are
 * acceptable.
 *
 * First, take existing camel case and add a space between each word so that it is in Title Form; note that
 *   consecutive capitals (acronyms) are considered a single word.
 * Second, capture all contigious words, capitalize the first letter and then convert the rest into lower case.
 * Third, strip out all the non-desirable characters (i.e, non numerics).
 *
 * EXAMPLES:
 * $str = 'Please_RSVP: b4 you-all arrive!';
 *
 * To convert a string to camel case:
 *  strtocamel($str); // gives: PleaseRsvpB4YouAllArrive
 *
 * To convert a string to an acronym:
 *  strtocamel($str, true, 'A-Z'); // gives: PRBYAA
 *
 * To convert a string to first-lower camel case without numerics but with underscores:
 *  strtocamel($str, false, 'A-Za-z_'); // gives: please_RsvpBYouAllArrive
 *
 * @param  string  $str              text to convert to camel case.
 * @param  bool    $capitalizeFirst  optional. whether to capitalize the first chare (e.g. "camelCase" vs. "CamelCase").
 * @param  string  $allowed          optional. regex of the chars to allow in the final string
 *
 * @return string camel cased result
 *
 * @author Sean P. O. MacCath-Moran   www.emanaton.com
 */
function strtocamel($str, $capitalizeFirst = true, $allowed = 'A-Za-z0-9') {
    return
preg_replace(
        array(
           
'/([A-Z][a-z])/e', // all occurances of caps followed by lowers
           
'/([a-zA-Z])([a-zA-Z]*)/e', // all occurances of words w/ first char captured separately
           
'/[^'.$allowed.']+/e', // all non allowed chars (non alpha numerics, by default)
           
'/^([a-zA-Z])/e' // first alpha char
       
),
        array(
           
'" ".$1', // add spaces
           
'strtoupper("$1").strtolower("$2")', // capitalize first, lower the rest
           
'', // delete undesired chars
           
'strto'.($capitalizeFirst ? 'upper' : 'lower').'("$1")' // force first char to upper or lower
       
),
       
$str
   
);
}
Jaason
10.07.2009 10:48
convert polish special letters into big and small chars;p

<?php
function toUpper($string) {
    return (
strtoupper(strtr($string, 'ęóąśłżźćń','ĘÓĄŚŁŻŹĆŃ' )));
    };

function
toLower($string) {
    return (
strtolower(strtr($string,'ĘÓĄŚŁŻŹĆŃ', 'ęóąśłżźćń' )));
    };
?>
chris at table4 dot com
19.01.2009 16:31
Simple function to change the case of your string and any accented html characters contained within it.

Inspired by fullUpper(), by silent at gmx dot li... just a little bit more atomic.

<?php

function convertCase($str, $case = 'upper')
{
//yours, courtesy of table4.com  :)
 
switch($case)
  {
    case
"upper" :
    default:
     
$str = strtoupper($str);
     
$pattern = '/&([A-Z])(UML|ACUTE|CIRC|TILDE|RING|';
     
$pattern .= 'ELIG|GRAVE|SLASH|HORN|CEDIL|TH);/e';
     
$replace = "'&'.'\\1'.strtolower('\\2').';'"; //convert the important bit back to lower
   
break;
   
    case
"lower" :
     
$str = strtolower($str);
    break;
  }
 
 
$str = preg_replace($pattern, $replace, $str);
  return
$str;
}
?>

Depending on what you are trying to achieve you would call like this:

<?php

//with entities...
$str = convertCase(htmlentities($str, ENT_QUOTES, "ISO-8859-1"));

?>
spaceman at foo dot at
17.04.2008 18:59
It has been mentioned in a previous comment that all you need to do to let PHP's strtoupper() do the conversion - instead of writing more or less complicated functions yourself - is to specify the locale in which you're doing the case conversion:

<?php setlocale(LC_CTYPE, "de_AT") ?>

It is important to note that setlocale() will silently fail if it can't find the specified locale on your system, so *always* check its return value. Try different spellings: using "de_AT" as an example, there are various combinations that may or may not work for you: "de", "de_AT.utf8", "de_AT.iso-8859-1", "de_AT.latin1", "de_AT@euro", etc).

If you can't find an appropriate locale setting, check your system configuration (locales are a system-wide setting, PHP gets them from the OS). On Windows, locales can be set from the Control Panel; on Linux it depends on your distribution. You can try "sudo dpkg-reconfigure locales" on Debian-based distros, or configure them manually. On Ubuntu Dapper, I had to copy entries over from /usr/share/i18n/SUPPORTED to /var/lib/locales/supported.d/local, then do the dpkg-reconfigure.

After you're done, restart the web server.

That said, there are special cases where you want to do the conversion manually. In German, for example, the letter 'ß' (szlig) only exists as a lower-case character, and so doesn't get converted by strtoupper. The convential way to express a 'ß' in an uppercase string is "SS". This function will take care of this exception (for Latin1 and most of Latin9, at least):

<?php

define
("LATIN1_UC_CHARS", "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝ");
define("LATIN1_LC_CHARS", "àáâãäåæçèéêëìíîïðñòóôõöøùúûüý");

function
uc_latin1 ($str) {
   
$str = strtoupper(strtr($str, LATIN1_LC_CHARS, LATIN1_UC_CHARS));
    return
strtr($str, array("ß" => "SS"));
}

?>
jesdisciple at gmail dot com
9.03.2008 2:02
This function takes a space-delimited list of words and returns it as one camelcase word.
<?php
function strtocamel($str){
   
$str = explode(' ', strtolower($str));
    for(
$i = 1; $i < count($str); $i++){
       
$str[$i] = strtoupper(substr($str[$i], 0, 1)) . substr($str[$i], 1);
    }
    return
implode('', $str);
}
?>

Example:
<?php
echo strtocamel('Str tO CAMEL');
?>
This will output 'strToCamel'.  To also make the first letter uppercase, change '$i = 1' to '$i = 0'.
silent at gmx dot li
15.10.2007 14:25
ISO-8859-1 (Latin 1) full with all special characters:

<?php
function fullUpper($str){
  
// convert to entities
  
$subject = htmlentities($str,ENT_QUOTES);
  
$pattern = '/&([a-z])(uml|acute|circ';
  
$pattern.= '|tilde|ring|elig|grave|slash|horn|cedil|th);/e';
  
$replace = "'&'.strtoupper('\\1').'\\2'.';'";
  
$result = preg_replace($pattern, $replace, $subject);
  
// convert from entities back to characters
  
$htmltable = get_html_translation_table(HTML_ENTITIES);
   foreach(
$htmltable as $key => $value) {
     
$result = ereg_replace(addslashes($value),$key,$result);
   }
   return(
strtoupper($result));
}

echo
fullUpper("try this: äöüß");
?>

results in

TRY THIS: ÄÖÜß
Oliv.
11.10.2007 16:20
accents convertion trick :

<?php
       
   
function ucfirstHTMLentity($matches){
        return
"&".ucfirst(strtolower($matches[1])).";";
    }
    function
fullUpper($str){
       
$subject = strtoupper(htmlentities($str, null, 'UTF-8'));
       
$pattern = '/&([A-Z]+);/';
        return
preg_replace_callback($pattern, "ucfirstHTMLentity", $subject);
    }

        print
fullUpper($_REQUEST["txt"]);
   
?>
xguimax at gmail dot com
5.10.2007 22:17
Portuguese version of String Capitalize in PHP.

    function strProper($str)
    {
        $noUp = array('um','uma','o','a','de','do','da','em');
        $str = trim($str);
        $str = strtoupper($str[0]) . strtolower(substr($str, 1));
        for($i=1; $i<strlen($str)-1; ++$i) {
            if($str[$i]==' ') {
                for($j=$i+1; $j<strlen($str) && $str[$j]!=' '; ++$j); //find next space
                $size = $j-$i-1;
                $shortWord = false;
                if($size<=3) {
                    $theWord = substr($str,$i+1,$size);
                    for($j=0; $j<count($noUp) && !$shortWord; ++$j)
                        if($theWord==$noUp[$j])
                            $shortWord = true;
                }
                if( !$shortWord )
                    $str = substr($str, 0, $i+1) . strtoupper($str[$i+1]) . substr($str, $i+2);
            }  
            $i+=$size;
        }
        return $str;
    }
marcinhacia at gazeta dot pl
31.07.2007 17:15
In response to strtoupper:

There is a simpler way to change the first letter of a string to uppercase:

<?php
$string
='this is a much more simpler way to capitalise the first character of a string';
echo
ucfirst($string); // This is a much more...
?>

16.05.2007 10:40
<?php
$string
='this is a simpler way to capitalise the first character of a string';
$string[0]=strtoupper($string[0]);
echo
$string; // This is a simpler way...
?>
RUNET
18.04.2007 2:33
Russian

function str_to_upper($str){
    return strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\xE0\xE1\xE2\xE3\xE4\xE5".
    "\xb8\xe6\xe7\xe8\xe9\xea".
    "\xeb\xeC\xeD\xeE\xeF\xf0".
    "\xf1\xf2\xf3\xf4\xf5\xf6".
    "\xf7\xf8\xf9\xfA\xfB\xfC".
    "\xfD\xfE\xfF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\xC0\xC1\xC2\xC3\xC4\xC5".
    "\xA8\xC6\xC7\xC8\xC9\xCA".
    "\xCB\xCC\xCD\xCE\xCF\xD0".
    "\xD1\xD2\xD3\xD4\xD5\xD6".
    "\xD7\xD8\xD9\xDA\xDB\xDC".
    "\xDD\xDE\xDF");
}
Cory
24.07.2006 6:05
This function converts any series of english words to Proper Casing.  It also accounts for words such as 'a' and 'the'.  To change what words are ignored, just change the $noUp array.

function strProper($str) {
    $noUp = array('a','an','of','the','are','at','in');
    $str = trim($str);
    $str = strtoupper($str[0]) . strtolower(substr($str, 1));
    for($i=1; $i<strlen($str)-1; ++$i) {
        if($str[$i]==' ') {
            for($j=$i+1; $j<strlen($str) && $str[$j]!=' '; ++$j); //find next space
            $size = $j-$i-1;
            $shortWord = false;
            if($size<=3) {
                $theWord = substr($str,$i+1,$size);
                for($j=0; $j<count($noUp) && !$shortWord; ++$j)
                    if($theWord==$noUp[$j])
                        $shortWord = true;
            }
            if( !$shortWord )
                $str = substr($str, 0, $i+1) . strtoupper($str[$i+1]) . substr($str, $i+2);
        }   
        $i+=$size;
    }
    return $str;
}
sjrd at redaction-developpez dot com
3.06.2006 20:12
Angus Lord's function has got a problem with html entities such as &amp;, for they're converted into &Amp;, which is incorrect.

The following code fixes the problem:

<?php
function to_upper($string)
{
 
$new_string = "";
  while (
eregi("^([^&]*)(&)(.)([a-z0-9]{2,9};|&)(.*)", $string, $regs))
  {
   
$entity = $regs[2].strtoupper($regs[3]).$regs[4];
    if (
html_entity_decode($entity) == $entity)
     
$new_string .= strtoupper($regs[1]).$regs[2].$regs[3].$regs[4];
    else
     
$new_string .= strtoupper($regs[1]).$entity;
   
$string = $regs[5];
  }
 
$new_string .= strtoupper($string);
  return
$new_string;
}
?>
bart at insane dot at
10.05.2006 13:31
When using UTF-8 and need to convert to uppercase with
special characters like the german ä,ö,ü (didn't test for french,polish,russian but think it should work, too) try this:

function strtoupper_utf8($string){
    $string=utf8_decode($string);
    $string=strtoupper($string);
    $string=utf8_encode($string);
    return $string;
}
tree2054 at hotmail dot com
14.02.2006 19:11
An even simpler version of h3's rewrite:

<?php
function isupper($i) { return (strtoupper($i) === $i);}
function
islower($i) { return (strtolower($i) === $i);}
?>
Grkem PAACI(gorkempacaci[et]gmail.com)
6.01.2006 3:36
These functions can be used on Turkish(iso-8859-9):
Turkce(iso-8859-9) icin su fonksiyonlar kullanilabilir:

$tr_low_letters = str_split("abcdefghijklmnopqrstuvwxyz");
$tr_up_letters = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
function tr_uppercase($str) {
    global $tr_low_letters, $tr_up_letters;
    return str_replace($tr_low_letters, $tr_up_letters, $str);
}
function tr_lowercase($str) {
    global $tr_low_letters, $tr_up_letters;
    return str_replace($tr_up_letters, $tr_low_letters, $str);
}
function tr_fuppercase($str) {//only first letter uppercase
    return tr_uppercase($str[0]) . tr_lowercase(substr($str,1));
}
Vadim from Baku
27.11.2005 10:55
The following function counts uppercase letters in English and Cyrillic. It works great with cyrillic when strtolower doesn't work due to enviroment settings.(Thank you Sean!).

preg_match_all("@[A-Z-]@",$str,$m,PREG_OFFSET_CAPTURE)

It is probably displayed incorrectly due to page encoding, but there are range from the first uppercase letter of the latin alphabet to the last one and range from the first uppercase cyrillic alphabet letter to the last one in the pattern. Not sure but similar approach can work for other alphabets.
Beniamin
26.11.2005 3:04
Here is correct str2upper function for polish programmers (plus str2lower function):

<?php
function str2upper($text){
   return
strtr($text,
  
"abcdefghijklmnopqrstuvwxyz".
  
"\xB1\xE6\xEA\xB3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
  
"\xB9\x9C\x9F", // win 1250
  
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".
  
"\xA1\xC6\xCA\xA3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
  
"\xA5\x8C\x8F"  // win 1250
  
);
}

function
str2lower($text){
   return
strtr($text,
  
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".
  
"\xA1\xC6\xCA\xA3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
  
"\xA5\x8C\x8F"// win 1250
  
"abcdefghijklmnopqrstuvwxyz".
  
"\xB1\xE6\xEA\xB3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
  
"\xB9\x9C\x9F" // win 1250
  
);
}
?>
julas
1.08.2005 12:46
The code for Polish programmers was spolied a little bit - \xB3 should be turned into \xA3, not the opposite. So the correct code is:

function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xA3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xB3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );
}
kirsman
7.07.2005 19:37
For polish programmers:

function str2upper($text){
   return strtr($text,
   "abcdefghijklmnopqrstuvwxyz".
   "\xB1\xE6\xEA\xA3\xF1\xF3\xB6\xBC\xBF". // ISO 8859-2
   "\xB9\x9C\x9F", // win 1250
   "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   "\xA1\xC6\xCA\xB3\xD1\xD3\xA6\xAC\xAF". // ISO 8859-2
   "\xA5\x8C\x8F"  // win 1250
   );

30.05.2005 15:11
// 2005/5/30 Justin
    // Chinese_Traditional toupper
    function CT_to_upper($string)
    {       
        $isChineseStart = false;
       
          $new_string = "";
         $i = 0;
          while($i < strlen($string))
          {                  
               if (ord(substr($string,$i,1)) <128)
               {
                   if( $isChineseStart == false )
                       $new_string .= strtoupper(mb_substr($string,$i,1));
                   else      
                       $new_string .= substr($string,$i,1);
               }
               else
               {
                   if( $isChineseStart == false )
                       $isChineseStart = true;
                   else
                       $isChineseStart = false;                      
                    
                     $new_string .= substr($string,$i,1);
               }
               $i++;
          }
          return $new_string;         
    }
    //
Justin_Lin at mail2000 dot com dot tw
30.05.2005 15:09
The following is my code for translate a given string to upper case and it will support chinese traditional :

// 2005/5/30 Justin
// Chinese_Traditional toupper
function CT_to_upper($string)
{       
    $isChineseStart = false;
       
    $new_string = "";
    $i = 0;
    while($i < strlen($string))
    {                  
           if (ord(substr($string,$i,1)) <128)
            {
           if( $isChineseStart == false )
                $new_string .= strtoupper(mb_substr($string,$i,1));
           else      
                $new_string .= substr($string,$i,1);
             }
             else
             {
           if( $isChineseStart == false )
                  $isChineseStart = true;
           else
                $isChineseStart = false;                                 
             $new_string .= substr($string,$i,1);
             }
             $i++;
      }
      return $new_string;         
}
//
willyann at gmail dot com
25.05.2005 6:31
chinese

function to_upper($string) {
  $new_string = "";
  $i = 0;
  while($i < strlen($string)) {
   if (ord(substr($string,$i,1)) <128)
   {
     $new_string .= strtoupper(substr($string,$i,1));
     $i++;
   } else {
     $new_string .= substr($string,$i,2);
     $i=$i+2;
   }
  }
  return $new_string;
}

13.03.2005 2:08
Ah, the last code were spoiled, here is the fixed one:

<?php

function str_to_upper($str){
    return
strtr($str,
   
"abcdefghijklmnopqrstuvwxyz".
   
"\x9C\x9A\xE0\xE1\xE2\xE3".
   
"\xE4\xE5\xE6\xE7\xE8\xE9".
   
"\xEA\xEB\xEC\xED\xEE\xEF".
   
"\xF0\xF1\xF2\xF3\xF4\xF5".
   
"\xF6\xF8\xF9\xFA\xFB\xFC".
   
"\xFD\xFE\xFF",
   
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".
   
"\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
   
"\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
   
"\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
   
"\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
   
"\xDB\xDC\xDD\xDE\x9F");
}

?>

So, this function changes also other letters into uppercase, strtoupper() does only change: a-z to: A-Z.

31.10.2004 0:23
If you only need to extend the conversion by the characters of a certain language, it's possible to control this using an environment variable to change the locale:

setlocale(LC_CTYPE, "de_DE");
p dot thomas at inlive dot info
3.04.2004 2:02
Some bench :

String Copy, OUT=IN : 21.398067474365 ms

String TRANSFORMATION :

- strtolower : 383.09001922607 ms
- strtolower( strtr) : 267.36092567444 ms
- preg_replace : 16624.928951263 ms
- stringUpDown : 4013.0908489227 ms

IN : jehrjzh r''_- &(r&) EAZREZREZ^m
OUT : jehrjzh r''_- &(r&) eazrezrez^m

Platform : AMD 1 Ghz, Win2K, EasyPHP
martine
7.02.2004 4:41
This may save you time and effort (if you need to convert european languages such as Czech, Portugees, German or Swedish)

the function mb_strtoupper() converts all accented characters in the latin alphabet, ie. , , , etc. This is easier than some of the suggestions below. It should also convert case properly for russian, etc.
mec at stadeleck dot org
2.12.2002 15:54
something I myself first not thought about:
if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).
urudz at strategma dot bg
21.04.2002 18:49
on linux
php gets LC_LOCAL env variable therefor you must set this

export LC_ALL=bg_BG.CP1251
export LANG=bg_BG.CP1251

before starting of apache i have put this to lines in /etc/rc.d/rc.httpd
-----

cat /etc/rc.d/rc.httpd
#!/bin/sh
#
# Start the Apache web server
#

export LC_ALL=bg_BG.CP1251
export LANG=bg_BG.CP1251

case "$1" in
   'start')
      /usr/sbin/apachectl startssl ;;
   'stop')
      /usr/sbin/apachectl stop ;;
   'restart')
      /usr/sbin/apachectl restart ;;
   *)
      echo "usage $0 start|stop|restart" ;;
esac
-------

in windows you must define your "locale"
in control panel  > regional options > general

best regards urudz :>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)