4.1 案例介紹
處理項目中的各種字符串
4.2 分析案例
用字符串函數(shù)根據(jù)需求處理字符串巾表。
4.3 核心知識
字符串的定義
---單引號定義(轉義\'和\\)
---雙引號定義(轉義\n \r \t \$ \\ \")
---定界符方法<<<eof
字符串函數(shù)
4.4 知識講解
4.4.1字符串的定義
string是一系列字符冷冗。在?PHP 中溯乒,字符和字節(jié)一樣兴枯,也就是說,一共有?256 種不同字符的可能性对途。這也暗示?PHP 對?Unicode 沒有本地支持斯够。
注: 一個字符串變得非常巨大也沒有問題,PHP 沒有給字符串的大小強加實現(xiàn)范圍江兢,所以完全沒有理由擔心長字符串昨忆。
語法:
字符串可以用三種字面上的方法定義:
—— 單引號 ‘‘和``
—— 雙引號 ““
—— 定界符<<<
單引號
指定一個簡單字符串的最簡單的方法是用單引號(’)括起來。
例如:?$str1=‘phpchina’; ??//字符串str1賦值
用于單引號字符串的轉義序列\(zhòng)’解釋為一個單引號杉允,\\解釋為一個反斜杠(\)邑贴。任何其他反斜線的出現(xiàn)僅僅被解釋為一個反斜杠。
注: 和其他兩種語法不同叔磷,單引號字符串中出現(xiàn)的變量和轉義序列不會被變量的值替代拢驾。
雙引號
如果用雙引號(“)括起字符串,PHP 懂得更多特殊字符的轉義序列:
轉義字符:
?\” 雙引號 ?\n 換行
?\r 回車 ?\t 制表符
?\\ 反斜杠 ?\$ 美元符
?\{ 左大括號 ?\}? 右大括號
?\[ 左中括號 ?\] 右中括號
此外改基,如果試圖轉義任何其它字符繁疤,反斜線本身也會被顯示出來!
雙引號字符串最重要的一點是其中的變量名會被變量值替代。
<?php
$aa=‘a(chǎn)a’;
?? print(‘a(chǎn)a is \’aa\’’."<br/>");
?? print("aa is \"aa\""."<br/>");
?? print("aa is ‘a(chǎn)a’"."<br/>");
?? print(‘a(chǎn)a is "aa"‘."<br/>");
?? print(“aa is $aa”.“<br>“);//變量被值替換
print(“aa is {$aa}”.“<br>“);//大括號分離變量
?? print(‘a(chǎn)a is $aa’."<br>");
?? print(‘a(chǎn)a is ‘.$aa);
?>
定界符
另一種給字符串定界的方法使用定界符語法:(“<<<“)稠腊。應該在<<<之后提供一個標識符案疲,然后是字符串,然后是同樣的標識符結束字符串麻养。結束標識符必須從行的第一列開始褐啡。定界符文本表現(xiàn)的就和雙引號字符串一樣,在定界符文本中不需要轉義引號鳖昌。
<?php
$my_quote=<<<here
"Put your hand on a hot stove for a minute, and it seems like an hour. Sit with a pretty girl for an hour, and it seems like a minute.here;
echo $my_quote;
?>
4.4.2打印字符串(字符串的輸出)函數(shù)
echo( )
語法: echo "string arg1, string [argn]...";
它是語言結構备畦,不是真正的函數(shù)。它和print的區(qū)別在于许昨,可以接受多個參數(shù)懂盐。
例如:
echo“first”,”second”,”third”;//合法
echo (“hello”,”world!”); //解析錯誤
print( )
語法: int print(string arg);
本函數(shù)輸出字符串。若成功則返回1糕档,失敗則返回 0莉恼。例如傳輸中途客戶的瀏覽器突然掛了,則會造成輸出失敗的情形速那。
例如:if(!print(“Hello,world”))
?? {
die(“you’re not listening to me!”);
?? }
4.4.3 ucfirst( )
ucfirst()將字符串第一個字符改大寫俐银。?
語法: string ucfirst(string str);
返回值: 字符串
本函數(shù)返回字符串?str 第一個字的字首字母改成大寫。
<?php$foo?=?’hello?world!’;$foo?=?ucfirst($foo);????????????? ?//?Hello?world!$bar?=?’HELLO?WORLD!’;$bar?=?ucfirst($bar);????????????? ??//?HELLO?WORLD!$bar?=?ucfirst(strtolower($bar));?//?Hello?world!
?>
4.4.4 ucwords( )
ucwords()將字符串每個字第一個字母改大寫端仰。?
語法: string ucwords(string str);
返回值: 字符串
本函數(shù)返回字符串?str 每個字的字首字母全都改成大寫捶惜。
<?php$foo?=?’hello?world!’;$foo?=?ucwords($foo);?????????????//?Hello?World!?$bar?=?’HELLO?WORLD!’;$bar?=?ucwords($bar);?????????????//?HELLO?WORLD!$bar?=?ucwords(strtolower($bar));?//?Hello?World!
?>
4.4.5格式化字符串以便顯示
函數(shù):sprintf() --將字符串格式化。?
語法: string sprintf(string format, mixed [args]...);
返回值: 字符串
本函數(shù)用來將字符串格式化荔烧。參數(shù)?format 是轉換的格式吱七,以百分比符號?% 開始到轉換字符為止。
轉換說明的類型碼如下:
b 整數(shù)轉成二進位鹤竭。?
c 整數(shù)轉成對應的?ASCII 字符踊餐。?
d 整數(shù)轉成十進位。?
f 單倍精確度數(shù)字轉成浮點數(shù)臀稚。?
o 整數(shù)轉成八進位吝岭。?
s 轉成字符串。?
x 整數(shù)轉成小寫十六進位烁涌。?
X 整數(shù)轉成大寫十六進位苍碟。
printf( )
輸出格式化字符串酒觅。
語法: int printf(string format, mixed [args]...);
返回值: 整數(shù)?
本函數(shù)依參數(shù)?format 指定的內(nèi)容格式將字符串格式化撮执,同sprintf()。
<?php
?? printf("1...the character value of %d is %c",72,72)
?? printf("2...control the number of decimal in %f with %.2f",5.1234,5.1234);
?? printf("3...we can also left-pad number with zeros: %05f",33.22);
printf("4...or we can left-pad number and special precision : %5.2f",33.22);
printf("5...the hexadecimal representation of %d is %x",92,92);
printf("6...but you can also write it as %X",92);
printf("7...and if you were wondering, its octal representation is %o",92);
printf("8...left-pad the string %s with dashes, like so: %’*6s",’foo’,’bar’);
printf("9...and now let’s right-pad it with dashes: %’*-6s",’foo’,’bar’);
?>
4.4.6 explode()
使用一個字符串分割另一個字符串?
語法:array explode ( string separator, string string [, int limit] )
此函數(shù)返回由字符串組成的數(shù)組舷丹,每個元素都是?string 的一個子串抒钱,它們被字符串?separator?作為邊界點分割出來。如果設置了?limit?參數(shù),則返回的數(shù)組包含最多?limit?個元素谋币,而最后那個元素將包含?string?的剩余部分仗扬。
例如:
$pizza??= "piece1 piece2 piece3";
$pieces = explode(“ ?", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
4.4.7 implode()
用一組較小的字符串創(chuàng)建一個大字符串。
格式:string implode ( string glue, array pieces )
第一個參數(shù)glue是放在第二個參數(shù)pieces的元素之間的字符串蕾额≡绨牛可以像下面這樣重建簡單的逗號分隔的字符串。
例如:
$array = array(‘lastname’, ‘email’, ‘phone’);$comma_separated = implode(“,”, $array);echo $comma_separated; //顯示lastname,email,phone
4.4.8 str_split( )
將字符串轉為數(shù)組诅蝶。?
語法: array str_split ( string $string [, int $split_length = 1 ] );
返回值: 數(shù)組
本函數(shù)用來將一個字符串按規(guī)定個數(shù)劃分為數(shù)組退个。第二個參數(shù)作為可選參數(shù)規(guī)定每幾個字符進行一次劃分。
<?php$str?=?’abcdef’;print_r(?str_split($str));?//?array(‘a(chǎn)’,’b’,’c’,’d’,’e’,’f’);
print_r(?str_split($str,2));?//?array(‘a(chǎn)b’,’cd’,’ef’);
?>
4.4.9 strlen( )
取得字符串長度调炬。
語法: int strlen(string str);
返回值: 整數(shù)?
本函數(shù)返回指定的字符串長度语盈。
<?php$str?=?’abcdef’;echo?strlen($str);?//?6$str?=?’?ab?cd?’;echo?strlen($str);?//?7
?>
4.4.10 substr( )
取部份字符串。?
語法: string substr(string string, int start, int [length]);
返回值: 字符串?
本函數(shù)將字符串?string 的第?start 位起的字符串取出?length 個字符缰泡,若省略參數(shù)?length刀荒,則取到字符串末尾?。若?start 為負數(shù)棘钞,則從字符串尾端往前開始提取缠借。如果length為整數(shù),表示返回length個字符宜猜,若為負數(shù)烈炭,則表示取到倒數(shù)第?length 個字符。
<?phpecho?substr(‘a(chǎn)bcdef’,?1);?????//?bcdefecho?substr(‘a(chǎn)bcdef’,?1,?3);??//?bcdecho?substr(‘a(chǎn)bcdef’,?0,?4);??//?abcdecho?substr(‘a(chǎn)bcdef’,?0,?8);??//?abcdefecho?substr(‘a(chǎn)bcdef’,?-1,?1);?//?f//?Accessing?single?characters?in?a?string//?can?also?be?achived?using?"curly?braces"$string?=?’abcdef’;echo?$string{0};?????????????????//?aecho?$string{3};?????????????????//?decho?$string{strlen($string)-1};?//?f
?>
4.4.11 strstr( ) ?別名:strchr( )
返回字符串中某字符串開始處至結束的字符串宝恶。
語法: string strstr(string haystack, string needle);
返回值: 字符串?
本函數(shù)將?needle 最先出現(xiàn)在?haystack 處起至?haystack 結束的字符串返回符隙。若找不到?needle 則返回?false。
4.4.12 strrchr()
取得某字符最后出現(xiàn)的位置字符串垫毙。?
語法: string strrchr(string haystack, string needle);
本函數(shù)用來尋找字符串?haystack 中的字符?needle 最后出現(xiàn)位置霹疫,并將此位置起至字符串?haystack 結束之間的字符串返回。若沒有找到?needle 則返回?false综芥。?
<?php//?get?last?directory?in?$PATH$dir?=?substr(strrchr($PATH,?":"),?1);//?get?everything?after?last?newline$text?=?"Line?1\nLine?2\nLine?3";$last?=?substr(strrchr($text,?10),?1?);
?>
4.4.13 strpos()
尋找字符串中某字符最先出現(xiàn)的位置丽蝎。默認從?0 開始。?
語法: int strpos(string haystack, string needle, int [offset]);
本函數(shù)用來尋找字符串?haystack 中的字符?needle 最先出現(xiàn)的位置膀藐。若找不到指定的字符屠阻,則返回?false 值。參數(shù)?offset 可省略额各,用來表示從?offset 開始找国觉。
<?php$mystring?=?’abc’;$findme???=?’a’;$pos?=?strpos($mystring,?$findme);//?Note?our?use?of?===.??Simply?==?would?not?work?as?expected//?because?the?position?of?’a’?was?the?0th?(first)?character.if?($pos?===?false)?{????echo?"The?string?’$findme’?was?not?found?in?the?string?’$mystring’";}?else?{????echo?"The?string?’$findme’?was?found?in?the?string?’$mystring’";????echo?"?and?exists?at?position?$pos";}//?We?can?search?for?the?character,?ignoring?anything?before?the?offset$newstring?=?’abcdef?abcdef’;$pos?=?strpos($newstring,?’a’,?1);?//?$pos?=?7,?not?0
?>
4.4.14 strrpos( )
尋找字符串中某字符最后出現(xiàn)的位置。
語法: int strrpos(string haystack, char needle);
返回值: 整數(shù)
本函數(shù)用來尋找字符串?haystack 中的字符?needle 最后出現(xiàn)的位置虾啦。若找不到指定的字符麻诀,則返回?false 值痕寓。
<?php//?in?PHP?4.0.0?and?newer:$pos?=?strrpos($mystring,?"b");if?($pos?===?false)?{?//?note:?three?equal?signs????//?not?found...}//?in?versions?older?than?4.0.0:$pos?=?strrpos($mystring,?"b");if?(is_bool($pos)?&&?!$pos)?{????//?not?found...}
?>
4.4.15 str_pad()
str_pad()可以用于一些敏感信息的保護,如金額的打印蝇闭。
有4個參數(shù)呻率。第一個參數(shù)指明要處理的字符串,第二個參數(shù)給定處理后字符串的長度呻引。第三個字符串給出填補所用的字符串礼仗,默認使用空格進行填補。最后一個參數(shù)指定填補的方向逻悠,它有3個可選值:
STR_PAD_LEFT ???字符串左添補
STR_PAD_RIGHT 字符串右添補
STR_PAD_BOTH ?字符串兩端添補
<?php$input?=?"Alien";echo?str_pad($input,?10);??????????????????????//?produces?"Alien?????"echo?str_pad($input,?10,?"-=",?STR_PAD_LEFT);??//?produces?"-=-=-Alien"echo?str_pad($input,?10,?"_",?STR_PAD_BOTH);???//?produces?"__Alien___"echo?str_pad($input,?6?,?"___");???????????????//?produces?"Alien_"
?>
4.4.16字符串的替換
str_replace()
字符串替換藐守,三種替換方式
str_replace(string $search, string $replace, string $str);
str_replace(array $search, string $replace, string $str);
str_replace(array $search, array $replace, string $str);
<?php//?Provides:?You?should?eat?pizza,?beer,?and?ice?cream?every?day$phrase??=?"You?should?eat?fruits,?vegetables,?and?fiber?every?day.";$healthy?=?array("fruits",?"vegetables",?"fiber");$yummy???=?array("pizza",?"beer",?"ice?cream");$newphrase?=?str_replace($healthy,?$yummy,?$phrase);//?Use?of?the?count?parameter?is?available?as?of?PHP?5.0.0$str?=?str_replace("ll",?"",?"good?golly?miss?molly!",?$count);echo?$count;?//?2//?Order?of?replacement?$str?????=?"Line?1\nLine?2\rLine?3\r\nLine?4\n";$order???=?array("\r\n",?"\n",?"\r");$replace?=?’<br?/>‘;//?Processes?\r\n’s?first?so?they?aren’t?converted?twice.?$newstr?=?str_replace($order,?$replace,?$str);//?Outputs:?apearpearle?pear$letters?=?array(‘a(chǎn)’,?’p’);$fruit???=?array(‘a(chǎn)pple’,?’pear’);$text????=?’a?p’;$output??=?str_replace($letters,?$fruit,?$text);echo?$output;?
?>
4.4.17處理URL
除了對HTML文字的處理,?在WEB開發(fā)時還要對URL地址進行處理蹂风。處理URL主要包括:
對URL字符串的解析
parse_url();(解析完整的URL轉變成數(shù)組)
parse_str();(解析請求字符串轉變成數(shù)組)
URL編碼處理
urlencode(); (替換所有非字母數(shù)字的字符卢厂,變?yōu)?后面跟兩位16進制,空格變?yōu)?號)
urldecode(); (對已%##編碼的URL進行解析還原)
rawurlencode(); (替換所有非字母數(shù)字的字符惠啄,變?yōu)?后面跟兩位16進制)?
rawurldecode(); (對已%編碼的URL進行解析還原)
構造查詢字符串等慎恒。
http_build_query();(生成?url-encoded 之后的請求字符串?)
<?php$url?=?’http://username:password@hostname/path?arg=value#anchor’;print_r(parse_url($url));$str?=?"first=value&arr[]=foo+bar&arr[]=baz";parse_str($str);echo?$first;??//?valueecho?$arr[0];?//?foo?barecho?$arr[1];?//?bazparse_str($str,?$output);echo?$output[‘first’];??//?valueecho?$output[‘a(chǎn)rr’][0];?//?foo?barecho?$output[‘a(chǎn)rr’][1];?//?baz$query_string?=?’foo=‘?.?urlencode($foo)?.?’&bar=‘?.?urlencode($bar);echo?’<a?href="mycgi?’?.?htmlentities($query_string)?.?’">‘;
?>
4.5 知識運用
在Web應用中,很多情況下需要對字符串進行處理和分析撵渡,通常涉及字符串的格式化融柬、連接與分割、比較趋距、查找等一系列操作粒氧。用戶和系統(tǒng)的交互也基本上是通過文字來進行的,因此系統(tǒng)對文本信息节腐,即字符串的處理非常重視外盯。