the function arraytolower will create duplicate entries since keys are case sensitive.
<?php
$array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');
$array = arraytolower($array);
?>
/*
Array
(
[test1] => asgafasdaad
[TEST2] => ASddhshsDGb
[TeSt3] => asdasda@asdadadASDASDgh
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
*/
I prefer this method
<?php
function arraytolower($array, $include_leys=false) {
if($include_leys) {
foreach($array as $key => $value) {
if(is_array($value))
$array2[strtolower($key)] = arraytolower($value, $include_leys);
else
$array2[strtolower($key)] = strtolower($value);
}
$array = $array2;
}
else {
foreach($array as $key => $value) {
if(is_array($value))
$array[$key] = arraytolower($value, $include_leys);
else
$array[$key] = strtolower($value);
}
}
return $array;
}
?>
which when used like this
<?php
$array = $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');
$array1 = arraytolower($array);
$array2 = arraytolower($array,true);
print_r($array1);
print_r($array2);
?>
will give output of
Array
(
[test1] => asgafasdaad
[TEST2] => asddhshsdgb
[TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
[test1] => asgafasdaad
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
strtolower
(PHP 4, PHP 5)
strtolower — Make a string lowercase
Description
string strtolower
( string
$str
)
Returns string with all alphabetic characters
converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
Parameters
-
str -
The input string.
Return Values
Returns the lowercased string.
Examples
Example #1 strtolower() example
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>
Notes
Note: This function is binary-safe.
See Also
- strtoupper() - Make a string uppercase
- ucfirst() - Make a string's first character uppercase
- ucwords() - Uppercase the first character of each word in a string
- mb_strtolower() - Make a string lowercase
dbers26 at gmail dot com ¶
4 years ago
patricia at steuerungb dot de ¶
5 years ago
When you're not sure, how the current locale is set, you might find the following function useful. It's strtolower for utf8-formatted text:
<?php
function strtolower_utf8($inputString) {
$outputString = utf8_decode($inputString);
$outputString = strtolower($outputString);
$outputString = utf8_encode($outputString);
return $outputString;
}
?>
It's not suitable for every occasion, but it surely gets in handy. I use it for lowering German 'Umlauts' like ä and ö.
fackelkind ¶
7 years ago
Nifty? :D
<?php
function is_lowercase ($str){
return ($str == strtolower ($str));
}
?>
marcin at maydesign dot pl ¶
3 years ago
strtolower(); doesn't work for polish chars
<?php strtolower("mĄkA"); ?>
will return: mĄka;
the best solution - use mb_strtolower()
<?php mb_strtolower("mĄkA",'UTF-8'); ?>
will return: mąka
on at niepodam dot pl ¶
1 year ago
If the input string is in different language that server locale, then you should use mb_strtolower() function.
leha_grobov ¶
4 years ago
the strtolower version to support most amount of languages including russian, french and so on:
<?php
function strtolower_utf8($string){
$convert_to = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
"ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
"з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
"ь", "э", "ю", "я"
);
$convert_from = array(
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
"Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
"З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
"Ь", "Э", "Ю", "Я"
);
return str_replace($convert_from, $convert_to, $string);
}
?>
rodrigoATsistemasparainternetDOTcomDOTbr ¶
4 years ago
<?php
function fullLower($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 = "'&'.strtolower('\\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(strtolower($result));
}
echo fullLower("Ã É Ò Õ ÚÙÛ");
//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
coder at bulgaria dot bg ¶
4 years ago
for cyrillic and UTF 8 use mb_convert_case
exampel
<?php
$string = "Австралия";
$string = mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
echo $string;
//output is: австралия
?>
rok dot kralj at gmail dot com ¶
6 years ago
Slovenian characters
<?php
function strtolower_slovenian($string)
{
$low=array("Č" => "č", "Ž" => "ž", "Š" => "š");
return strtolower(strtr($string,$low));
}
?>
toringe at infostill dot com ¶
5 years ago
This will work for all languages using ISO8859_1 - more code than many other but fast.
<?php
function strtolower_iso8859_1($s){
$i = strlen($s);
while ($i > 0) {
--$i;
$c =ord($s[$i]);
if (($c & 0xC0) == 0xC0) {
// two most significante bits on
if (($c != 215) and ($c != 223)){ // two chars OK as is
// to get lowercase set 3. most significante bit if needed:
$s[$i] = chr($c | 0x20);
}
}
}
return strtolower($s);
}
?>
marco at recchiuti dot it ¶
6 years ago
Maybe it is not so elegant, but it Works.
It's just a fast Idea and it is what I need.
Any hacks for other characters (link !, ? etc etc) should help.
function RemoveShouting($string)
{
$frase = "";
$astri = explode(".", $string);
foreach ($astri as $elem)
$frase .= " ".ucfirst(trim(strtolower($elem))).". ";
return trim($frase);
}
Cheers!
M
spiceee ddotty spiceee com ¶
7 years ago
If you ever need to strtolower a string with href tags on it and doesn't want to mess with the characters inside a tag, this is for you.
<?php
function loweroutsidetags ($str) {
$chars = preg_split ("//", $str);
$tolower = true;
$str = '';
foreach ($chars as $k) {
if ($k == '<') { $tolower = false; }
if ($tolower) { $k = strtolower ($k); }
$str .= $k;
if ($k == '>') { $tolower = true; }
}
return $str;
}
?>
this:
echo loweroutsidetags('aALalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">')
will give:
aalalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">
bkimble at ebaseweb dot com ¶
10 years ago
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website :) If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it's only the very first word of the string. I've also added some exceptions so you don't make things like roman numerals look like "Iii" or "Xcmii" or something.
function RemoveShouting($string)
{
$lower_exceptions = array(
"to" => "1", "a" => "1", "the" => "1", "of" => "1"
);
$higher_exceptions = array(
"I" => "1", "II" => "1", "III" => "1", "IV" => "1",
"V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
"XI" => "1", "X" => "1"
);
$words = split(" ", $string);
$newwords = array();
foreach ($words as $word)
{
if (!$higher_exceptions[$word]) $word = strtolower($word);
if (!$lower_exceptions[$word]) $word[0] = strtoupper($word[0]);
array_push($newwords, $word);
}
return join(" ", $newwords);
}
BK
tty01_at_rambler_dot_ru ¶
10 years ago
Another solution for Double-Byte-Characters, based on iconv() functions, not sensible to the current locale, works on win32.
/* Converts charset */
function myConvertCharset($str, $from, $to)
{
if(@function_exists('iconv'))
{
return iconv($from, $to, $str);
}
else if(@function_exists('recode_string'))
{
return recode_string($from . '..' . $to, $str);
}
else
{
print "function iconv not exists";
return $str;
}
}
/* Converts a string to lowercase */
function my_strtolower($s)
{
$t = "windows-1251";
$d = "UTF-8";
return myConvertCharset(strtolower(myConvertCharset($s, $d, $t)), $t, $d);
}
print my_strtolower("СЛОВО Uppercase");
ewertonp at hotmail dot com ¶
3 years ago
Here is my solution to lowercase strings Latin strings with accents. In this case I've used Brazilian Portuguese locale:
<?PHP
setlocale(LC_ALL, 'pt_BR');
echo strtolower('ÉÁÇÚÍÑ');
// output: éáçúíñ
echo ucfirst(strtolower('éÁÇÚÍÑ'));
// output: Éáçúíñ
?>
sanderwind at gmail dot com ¶
3 years ago
Very easy way to only make the first character lowercase:
<?php
function lcfirst($string) {
$string{0} = strtolower($string{0});
return $string;
}
?>
hans111 {AT} yahoo {DOT} com ¶
4 years ago
Could be useful, if mb string library is not available for whatever the reason:
<?php
function utf8_strtolower($string) {
return utf8_encode(strtolower(utf8_decode($string)));
}
##equally.....
function utf8_ucfirst($string) {
return utf8_encode(ucfirst(utf8_decode($string)));
}
#.....etc...
?>
It has worked for me, just make sure you feed the functions with the proper encoded text (utf-8)
[These functions] only work when translation is between common characters in ISO 8859-1 and UTF-8, that means they will work well with western languages but not cyrillic or asian.
s0urce at anonyme dot com ¶
4 years ago
for someone who needs - arraytolower:
<?php
function arraytolower($array,$round = 0){
foreach($array as $key => $value){
if(is_array($value)) $array[strtolower($key)] = $this->arraytolower($value,$round+1);
else $array[strtolower($key)] = strtolower($value);
}
return $array;
}
?>
converts the whole array in a levels. keys and values.
Patrick ¶
7 years ago
If you're considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:
<?php
function unhtmlentities($string)
{
// replace numeric entities
$string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
$string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
// replace literal entities
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
return strtr($string, $trans_tbl);
}
?>
That was copied exactly from the html_entity_decode manual page. It'll handle numeric entities correctly, the below function won't.
mhuggins57 at yahoo dot com ¶
7 years ago
There's a ucfirst "function" to make the first character uppercase, but there's no "lcfirst" function to make the first character lowercase. Here's my own code to accomplish this.
<?
function lcfirst($str) {
return strtolower(substr($str, 0, 1)) . substr($str, 1);
}
?>
I found this particularly useful for generating XML nodes with the Reflection class.
Anonymous ¶
10 years ago
This function is sensible to the current locale, namely the LC_CTYPE category (the default LC_CTYPE category is set from the LANG environment variable or by an explicit LC_CTYPE setting, but it can be overriden by the LC_ALL environment setting). If no locale setting is done in the enironment, the default locale will be C, for which the lowercase/uppercase conversion is based on the default character set of the system: this may convert only ASCII letters, or also ISO-8859-1 letters depending on the system...
maxim at inbox dot ru ¶
1 year ago
Nice idea to use static vars, here is my solution, i think, it is not very nice, when two very simular functions are separate. So :
<?php
function tocase($s,$up=false)
{
global $chars_hi, $chars_lo;
return $up?strtr($s, $chars_lo, $chars_hi):strtr($s, $chars_hi,$chars_lo);
}
?>
Just use second param when u need to uppercase, by default (false) it makes low, nice speed and small space :)
utilmind at gmail ¶
1 year ago
Everyone knows that strtolower/strtoupper does not translate cyrillic charactes (cp1251 code page). But I just was surprised that strtolower works twice(!) slower that translating characters with "strtr()".
Here is what I use to translate cyrillic (works for Russian, Ukrainian, Belorussian and cyrillic balcan languages, like Serbian etc):
<?php
// Arrays (REMOVE THE LINE BREAKS! THIS NOT WON'T BE POSTED WITH SUCH LONG LINES!)
$chars_hi = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ
АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁЂЃЄЅІЇЈЉЊЋЌЎЏҐ';
$chars_lo = 'abcdefghijklmnopqrstuvwxyz
абвгдежзийклмнопрстуфхцчшщъыьэюяёђѓєѕіїјљњћќўџґ';
// functions
function uppercase($s) {
global $chars_hi, $chars_lo;
return strtr($s, $chars_lo, $chars_hi);
}
function lowercase($s) {
global $chars_hi, $chars_lo;
return strtr($s, $chars_hi, $chars_lo);
}
?>
Remember, it works TWICE FASTER than strtoupper/strtolower! So maybe someone will would like to translate the arrays for another code pages different than cp1251
RCube ¶
2 years ago
To convert an entire array to lower, I prefer this method;
<?php
function arraytolower(array $array, $round = 0){
return unserialize(strtolower(serialize($array)));
}
?>
3 lines of code seem a lot less overhead than 10-40.
If there's any intrinsic problem with this method, please post it.
ghutix6 at gmail dot com ¶
4 years ago
Here is function for working polish lower letters (plus example):
<?php
function lower_pl($str)
{
return strtr($str, "ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQXV", "ąćęłńóśźżabcdefghijklmnoprstuwyzqxv");
}
$word ="ŻÓŁTKO";
$word = lower_pl ($word);
echo ("<p>$word</p>");
?>
This will turn into: <p>żółtko</p>.
HQ063 ¶
6 years ago
Similar to last function, but for spanish
function strtolower_es($string)
{
$low=array("Á" => "á", "É" => "é", "Í" => "í", "Ó" => "ó", "Ú" => "ú", "Ü" => "ü", "Ñ" => "ñ");
return strtolower(strtr($string,$low));
}
Enzo_01 at abv dot bg ¶
6 years ago
two functions what works with cyrilic text
function cyr_strtolower($a) {
$offset=32;
$m=array();
for($i=192;$i<224;$i++)$m[chr($i)]=chr($i+$offset);
return strtr($a,$m);
}
function cyr_strtoupper($a) {
$offset=32;
$m=array();
for($i=192;$i<224;$i++)$m[chr($i+$offset)]=chr($i);
return strtr($a,$m);
}
ex:
cyr_strtoupper("абвгде"); // АБВГДЕ
cyr_strtolower("АБВГДЕ"); // абвгде
red at iklanumum dot com ¶
7 years ago
I've seen this as a common use from script developers, so I would like to share the alternative way to compare 2 string (CASE INSENSITIVE) without using strtolower for faster process.
Use strcasecmp() for comparison purpose rather than comparing uncertain case of 2 string variables, because strcasecmp() is approximately 60% faster, moreover, the greater its string length the greater the difference,!
Ex. case :
$var1; -> could be a mixture of upper & lower case
$var2; -> could be a mixture of upper & lower case
To compare whether $var1 is exactly the same as $var2 (case insensitive manner):
Use -> if (strcasecmp($var1,$var2)==0)
rather than -> if (strtolower($var1)==strtolower($var2))
kmcdermott at perimeterinstitute dot ca ¶
8 years ago
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:
$Sql = "SELECT * FROM tablename WHERE LOWER(column_name) = '".strtolower($my_var)."'";
phpContrib (A T) esurfers d o t c o m ¶
8 years ago
<?php
$b=html_entity_decode(strtolower(htmlentities($a)));
?>
will convert to lowercase most accented vocals
(it will convert into À into à into )
This is not fast and clean code, it is just a quick oneliner to help you if you need a quick way to do it
Users with older versions of PHP can use:
$b=unhtmlentities(strtolower(htmlentities($a)));
// with unhtmlentities() as defined in the html_entity_decode() manual page:
function unhtmlentities ($string) {
$trans_tbl =get_html_translation_table (HTML_ENTITIES );
$trans_tbl =array_flip ($trans_tbl );
return strtr ($string ,$trans_tbl );
}
eduardor2k at redr2k dot com ¶
6 years ago
I changed it a bit and i found that it's better to put everything in lowercase, and rebuild the text the same way a teacher corrects a text, for now it only checks that the first letter after a point "." must be
in upper case.
function RemoveShouting($string)
{
$string = strtolower(trim($string));
for($i=0;$i<strlen($string);$i++){
if($i==0){$string[$i] = strtoupper($string[$i]);}
if($string[$i] == "."){
while($string[$i+1] == " "){
$i++;
}
$string[$i+1] = strtoupper($string[$i+1]);
$i++;
}
}
return $string;
}
this function would change:
Hi mi name is PETER. SOME TIMES I FORGOT TO DISABLE CAPS LOCK.
into:
Hi mi name is peter. Some times i forgot to disable caps lock.
mario dot kostelac at gmail dot com ¶
6 years ago
This is strtolower function for Croatian characters:
function strToLowerCro($string){
$string = strtolower($string);
$patterns[0] = '/Č/';
$patterns[1] = '/Ć/';
$patterns[2] = '/Ž/';
$patterns[3] = '/Š/';
$patterns[4] = '/Đ/';
$replacements[0] = 'č';
$replacements[1] = 'ć';
$replacements[2] = 'ž';
$replacements[3] = 'š';
$replacements[4] = 'đ';
$string = preg_replace($patterns, $replacements, $string);
return $string;
}
Enjoy...
Khigashi ¶
4 years ago
Here is my code, I made because of the accents contained in the latin languages [like the Portuguese of Brazil =)]
<?php
function deepLower($texto){
//Letras minúsculas com acentos
$texto = strtr($texto, "
ĄĆĘŁŃÓŚŹŻABCDEFGHIJKLMNOPRSTUWYZQ
XVЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ
ÂÀÁÄÃÊÈÉËÎÍÌÏÔÕÒÓÖÛÙÚÜÇ
", "
ąćęłńóśźżabcdefghijklmnoprstuwyzq
xvёйцукенгшщзхъфывапролджэячсмитьбю
âàáäãêèéëîíìïôõòóöûùúüç
");
return strtolower($texto);
}
?>
concepton at gmail dot com ¶
4 years ago
comment to "alexfort at list dot ru"
i think better to use this one
<?php
function strtolower_ru($text) {
$alfavitlover = array('ё','й','ц','у','к','е','н','г', 'ш','щ','з','х','ъ','ф','ы','в', 'а','п','р','о','л','д','ж','э', 'я','ч','с','м','и','т','ь','б','ю');
$alfavitupper = array('Ё','Й','Ц','У','К','Е','Н','Г', 'Ш','Щ','З','Х','Ъ','Ф','Ы','В', 'А','П','Р','О','Л','Д','Ж','Э', 'Я','Ч','С','М','И','Т','Ь','Б','Ю');
return str_replace($alfavitupper,$alfavitlover,strtolower($text));
}
?>
alexfort at list dot ru ¶
4 years ago
<?php
//solution to the Cyrillic and uft-8
function strtolower_Cyrillic($word) {
$alfavitlover = explode(',', 'ё,й,ц,у,к,е,н,г,ш,щ,з,х,ъ,ф,ы,
в,а,п,р,о,л,д,ж,э,я,ч,с,м,и,т,ь,б,ю');
$alfavitupper = explode(',', 'Ё,Й,Ц,У,К,Е,Н,Г,Ш,Щ,З,Х,Ъ,Ф,Ы,
В,А,П,Р,О,Л,Д,Ж,Э,Я,Ч,С,М,И,Т,Ь,Б,Ю');
for($wr=0;$wr<=count($alfavitlover);$wr++) {
$word = str_replace($alfavitupper[$wr], $alfavitlover[$wr], $word);
}
return $word;
}
echo strtolower_Cyrillic('СаШа+МаШа');
?>
tushar at sel2in dot com ¶
4 years ago
Quick and works for accented characters like á
Tested on linux and win apache+php5
<?php
function strtolower2($s){
$ln = strlen($s);
$ln1 = $ln -1;
for($i=0; $i < $ln; $i++){
$k = ord(substr($s, $i, 1));
if($k>=65 && $k <= 90){
if($i > 0){
$l1 = substr($s, 0, $i);
}else{
$l1 ='';
}
$l1 = $l1 . chr($k+32);
if($i < $ln1){
$l1 = $l1 . substr($s, $i + 1);
}
$s = $l1;
}
}
return $s;
}
?>
Piotr ¶
5 years ago
///charset=iso-8859-2
function strtolower_iso8592($string)
{
$low=array("ˇ" => "±", "Ć" => "ć", "Ę" => "ę", "Ł" => "ł", "Ó" => "ó", "¦" => "¶", "Ż" => "ż", "¬" => "Ľ", "Ń" => "ń");
return strtolower(strtr($string,$low));
}
mr dot blober at gmail dot com ¶
6 years ago
simple example for Polish characters
<?php
function strtolower_pl($str)
{
return strtr(strtolower($str), '[ĄĆĘŁŃÓŚŹŻ]', '[ąćęłńóśźż]');
}
?>
Dinçer Akay ¶
6 years ago
Turkish Character
<?php
function strtolower_tr($string)
{
$low=array("Ü" => "ü", "Ö" => "ö", "Ğ" => "ğ", "Ş" => "ş", "Ç" => "ç", "İ" => "i", "I" => "ı");
return strtolower(strtr($string,$low));
}
?>
