PHP中常用的字符串格式化函數(shù)總結(jié),php函數(shù)
Jun 13, 2016 am 09:20 AMPHP中常用的字符串格式化函數(shù)總結(jié),php函數(shù)
字符串的格式化就是將字符串處理為某種特定的格式。通常用戶從表單中提交給服務(wù)器的數(shù)據(jù)都是字符串的形式,為了達(dá)到期望的輸出效果,就需要按照一定的格式處理這些字符串后再去使用。經(jīng)常見到的字符串格式化函數(shù)如下圖所示:
注意:在PHP中提供的字符串函數(shù)處理的字符串,大部分都不是在原字符串上修改,而是返回一個格式化后的新字符串。
一、取出空格和字符串填補函數(shù)
空格也是一個有效的字符,在字符串中也會占據(jù)一個位置。用戶在表單輸入數(shù)據(jù)時,經(jīng)常在無意中會多輸入一些無意義的空格。因此PHP腳本在接收到通過表單處理過來的數(shù)據(jù)時,首先處理的就是字符串中多余的空格,或者其他一些沒有意義的符號。在PHP中可以通過ltrim()、rtrim()和trim()函數(shù)來完成這項工作。這三個函數(shù)的語法格式相同,但作用有所不同。他們的語法格式如下所示:
復(fù)制代碼 代碼如下:
string ltrim(string str[,string charlist])??????????????? //從字符串左側(cè)刪除空格或其他預(yù)定義字符
string rtrim(string str[,string charlist])????????????? //從字符串右側(cè)刪除空白字符或其他預(yù)定義字符
string trim(string str[,string charlist])????????????? //從字符串的兩端刪除空白字符或其他預(yù)定義字符
這三個函數(shù)分別用于從字符串的左、右和兩端刪除空白字符或其他預(yù)定義字符。處理后的結(jié)果都會以新字符串的形式返回,不會在原字符串上修改。其中第一個參數(shù)str是待處理的字符串,為必選項。第二個參數(shù)charlist是過濾字符串,用于指定希望去除的特殊符號,該參數(shù)為可選。如果不指定過濾字符串,默認(rèn)情況下會去掉下列字符。
★”":空格
★”0\”:NULL
★”\t”:制表符
★”\n”:新行
★”\r”:回車
此外還可以使用“..”符號指定需要去除的一個范圍,例如“0..9”或“a..z”表示去掉ASCII碼值中的數(shù)字和小字母。它們的使用代碼如下所示:
復(fù)制代碼 代碼如下:
$str = "123 This is a test ..."; //聲明一個測試字符串,左側(cè)為數(shù)字開頭,右側(cè)為省略號
echo ltrim($str,"0..9"); //過濾掉字符串左側(cè)的數(shù)字,輸出This is a test ...
echo rtrim($str,".") //過濾掉字符串右側(cè)的所有“.”,輸出:123 This is a test
echo trim($str,"0..9 A..Z ."); //過濾掉字符串兩端的數(shù)字和大寫字母還有“.”,輸出:his is a test
?>
不僅可以按需求過濾掉字符串中的內(nèi)容,還可以使用str_pad()函數(shù)按需求對字符串進(jìn)行填補??梢杂糜趯σ恍┟舾行畔⒌谋Wo,例如數(shù)據(jù)的對并排列等。其函數(shù)的原型如下所示:
復(fù)制代碼 代碼如下:
string str_pad(string input,int pad_length[,string pad_string[,int pad_type]])
該函數(shù)有4個參數(shù),第一個參數(shù)指明要處理的字符串。第二個參數(shù)給定處理后字符串的長度,如果該值小于原始字符串的長度,則不進(jìn)行任何操作。第三個參數(shù)指定填補時所用的字符串,它為可選參數(shù),如果沒有指定則默認(rèn)使用空格填補。最后一個參數(shù)指定填補的方向,它有三個可選值:STR_PAD_BOTH、STR_PAD_LEFT和STR_PAD_RIGHT,分別代表在字符串兩端、左和右進(jìn)行填補。也是一個可選參數(shù),如果沒有指定,則默認(rèn)值是STR_PAD_RIGHT。函數(shù)str_pad()的使用代碼如下所示:
復(fù)制代碼 代碼如下:
$str = "LAMP";
echo str_pad($str,10);???????? //指定長度為10,默認(rèn)使用空格在右邊填補“LAMP”
echo str_pad($str,10,"-="STR_PAD_LEFT);???? //指定長度為10,指定在左邊填補“-=-=-=LAMP”
echo str_pad($str,10,"_"STR_PAD_BOTH);???? //指定長度為10,指定在左邊填補“___LAMP___”
?>
二、字符串大小寫的轉(zhuǎn)換
在PHP中提供了4個字符串大小寫的轉(zhuǎn)換函數(shù),它們都只有一個可選參數(shù),即傳入要進(jìn)行轉(zhuǎn)換的字符串。可以直接使用這些函數(shù)完成大小寫轉(zhuǎn)換的操作。函數(shù)strtoupper()用于將給定的字符串全部轉(zhuǎn)換為大寫字母;函數(shù)strtolower()用于將給定的字符串全部轉(zhuǎn)換為小寫字母;函數(shù)ucfirst()用于將給定的字符串中的首字母轉(zhuǎn)換為大寫,其余字符不變;函數(shù)ucwords()用于將給定的字符串中全部以空格分割的單詞首字母轉(zhuǎn)換為大寫。下面的程序是這些函數(shù)的使用代碼,如下所示:
復(fù)制代碼 代碼如下:
$lamp = "lamp is composed of Linux 、Apache、MySQL and PHP";
echo strtolower($lamp); //輸出:lamp is composed of linux、apache、mysql and php
echo strtoupper($lamp); //輸出:LAMP IS CONPOSED OF LINUX、APACHE、MYSQL AND PHP
echo ucfirst($lamp); //輸出:Lamp is composed of Linux 、Apache、MySQL and PHP
echo ucwords($lamp); //輸出: Lamp Is Composed Of Linux 、Apache、MySQL And PHP
?>
這些函數(shù)只是按照他們說明描述的方式工作,要想確保一個字符串的首字母是大寫字母,而其余的都是小寫字母,就需要使用符合的方式。如下所示:
復(fù)制代碼 代碼如下:
$lamp = "lamp is composed of Linux 、Apache、MySQL and PHP";
echo ucfirst(strtolower($lamp)); //輸出:Lamp is composed of linux、apache、mysql and php
?>
三、和HTML標(biāo)簽相關(guān)的字符串格式化
HTML的輸入表單和URL上附加資源是用戶將數(shù)據(jù)提交給服務(wù)器的途徑,如果不能很好地處理,就有可能成為黑客攻擊服務(wù)器的入口。例如,用戶在發(fā)布文章時,在文章中如果包含一些HTML格式標(biāo)記或JavaScript的頁面轉(zhuǎn)向等代碼了,直接輸出顯示則一定會使用頁面的布局發(fā)生改變。因為這些代碼被發(fā)送到瀏覽器中,瀏覽器會按有效的代碼去解釋。所以在PHP腳本中,對用戶提交的數(shù)據(jù)內(nèi)容一定要先處理。在PHP中為我們提供了非常全面的HTML相關(guān)的字符串格式化函數(shù),可以有效地控制HTML文本的輸出。
①函數(shù)nl2br()
在瀏覽器中輸出的字符串“
”標(biāo)記換行,而很多人習(xí)慣使用“\n”作為換行符號,但瀏覽器中不識別這個字符串的換行符。即使有多行文本,在瀏覽器中顯示時也只有這一行。nl2br()函數(shù)就是在字符串中的每個新行“\n”之前插入HTML換行符“
”。該函數(shù)的使用如下所示:
復(fù)制代碼 代碼如下:
echo nl2br("One line.\nAnother line."); //在“\n”前加上“
”標(biāo)記
/*輸出以下兩行結(jié)果
One line.
Another line.
*/
?>
②函數(shù)htmlspecialchars()
如果不希望瀏覽器直接解析HTML標(biāo)記,就需要將HTML標(biāo)記中的特殊字符轉(zhuǎn)換成HTML實體。例如,將“”轉(zhuǎn)換為“>”。這樣HTML標(biāo)記瀏覽器就不會去解析,而是將HTML文本在瀏覽器中原樣輸出。PHP中提供的htmlspecialchars()函數(shù)就可以將一些預(yù)定義的字符串轉(zhuǎn)換為HTML實體。此函數(shù)用在預(yù)防使用者提供的文字中包含了HTML的標(biāo)記,像是布告欄或是訪客留言板這方面的應(yīng)用。以下是該函數(shù)可以轉(zhuǎn)換的字符:
★“&”(和號)轉(zhuǎn)換為“&”。
★“””(雙引號)轉(zhuǎn)換為“"”。
★“'”(單引號)轉(zhuǎn)換為“'”。
★“
★“>”(大于)轉(zhuǎn)換為“>”。
該函數(shù)的原型如下:
復(fù)制代碼 代碼如下:
string htmlspecialchars(string string [,int quote_style[,string charset]])
該函數(shù)中第一個參數(shù)是帶有HTML標(biāo)記待處理的字符串。第二個參數(shù)用來決定引號的轉(zhuǎn)換方式。默認(rèn)值為ENT_COMPAT將只轉(zhuǎn)換雙引號,而保留單引號;ENT_QUOTES將同時轉(zhuǎn)換這兩種引號;而ENT_NOQUOTES將不對引號進(jìn)行轉(zhuǎn)換。第三個參數(shù)用于指定所處理字符串的字符集,默認(rèn)的字符集是“ISO88511-1”。
復(fù)制代碼 代碼如下:
$str = "WebServer: & 'Linux' & 'Apache'"; //將有HTML標(biāo)記和單引號的字符串
echo htmlspecialchars($str,ENT_COMPAT); //轉(zhuǎn)換HTML標(biāo)記和轉(zhuǎn)換雙引號
echo "
\n";
echo htmlspecialchars($str,ENT_QUOTES); //轉(zhuǎn)換HTML標(biāo)記和轉(zhuǎn)換兩種引號
echo "
\n";
echo htmlspecialchars($str,ENT_NOQUOTES); //轉(zhuǎn)換HTML標(biāo)記和不對引號轉(zhuǎn)換
echo "
\n";
?>
在瀏覽器中的輸出結(jié)果
復(fù)制代碼 代碼如下:
WebServer: & ‘Linux' & ‘Apache'
WebServer: & ‘Linux' & ‘Apache'
WebServer: & ‘Linux' & ‘Apache'
如果在瀏覽器中查看源代碼,會看到如下結(jié)果:
復(fù)制代碼 代碼如下:
WebServer:&'Linux'&'Apache'
//沒有轉(zhuǎn)換單引號
WebServer:&'Linux'&'Apache'
WebServer:&'Linux'&'Apache' //沒有轉(zhuǎn)換單引號
在PHP中還提供了htmlentities()函數(shù),可以將所有的非ASCII碼字符轉(zhuǎn)換為對應(yīng)的實體代碼。該函數(shù)與htmlspecialchars()函數(shù)的使用語法格式一致,該函數(shù)可以轉(zhuǎn)義更多的HTML字符。下面的代碼為htmlentities()函數(shù)的使用范例:
復(fù)制代碼 代碼如下:
$str = "一個'quote'是bold";
//輸出&0qrave;??? 'quote' ê? <:b>bold
echo htmlentities($str);
//輸出:一個'quote' 是 bold
echo htmlentities($str,ENT_QUOTES,gb2312);
?>
在處理表單中提交的數(shù)據(jù)時,不僅要通過前面介紹的函數(shù)將HTML的標(biāo)記符號和一些特殊字符轉(zhuǎn)換為HTML實體,還需要對引號進(jìn)行處理。因為被提交的表單數(shù)據(jù)中的“'”、“””和“\”等字符前將自動加上一個斜線“\”。這是由于PHP配置文件php.ini中的選項magic_quotes_gpc在起作用,默認(rèn)是打開的,如果不關(guān)閉它則要使用函數(shù)stripslashes()刪除反斜線。如果不處理,將數(shù)據(jù)保存到數(shù)據(jù)庫中時,有可能會被數(shù)據(jù)庫誤當(dāng)成控制符號而引起錯誤。函數(shù)stripslashes()只有一個被處理字符串作為參數(shù),返回處理后的字符串。通常使用htmlspecialchars()函數(shù)與stripslashes()函數(shù)復(fù)合的方式,聯(lián)合處理表單中提交的數(shù)據(jù)。
函數(shù)stripslashes()的功能是去掉反斜線“\”,如果有連續(xù)兩個反斜線,則只去掉一個。與之對應(yīng)的是另一個函數(shù)addslashes(),正如函數(shù)名所暗示的,它將在“'”、“””、“\”和NULL字符等前增加必要的反斜線。
函數(shù)htmlspecialchars()是將函數(shù)HTML中的標(biāo)記符號轉(zhuǎn)換為對應(yīng)的HTML實體,有時直接刪除用戶輸入的HTML標(biāo)簽,也是非常有必要的。PHP中提供的strip_tags()函數(shù)默認(rèn)就可以刪除字符串中所有的HTML標(biāo)簽,也可以有選擇性地刪除一些HTML標(biāo)記。如布告欄或是訪客留言板,有這方面的應(yīng)用是相當(dāng)必要的。例如用戶在論壇中發(fā)布文章時,可以預(yù)留一些可以改變字體大小、顏色、粗體和斜體等的HTML標(biāo)記,而刪除一些對頁面布局有影響的HTML標(biāo)記。函數(shù)strip_tags()的原型如下所示:
復(fù)制代碼 代碼如下:
string strip_tags(string str[,string allowable_tags]); //刪除HTML的標(biāo)簽函數(shù)
該函數(shù)有兩個參數(shù),第一個參數(shù)提供了要處理的字符串,第二個參數(shù)是一個可選的HTML標(biāo)簽列表,放入該列表中的HTML標(biāo)簽將被保留,其他的則全部被刪除。默認(rèn)將所有HTML標(biāo)簽都刪除。下面的程序為該函數(shù)的使用范圍,如下所示:
復(fù)制代碼 代碼如下:
$str = "Linux Apache Mysql PHP";
echo strip_tags($str); //刪除了全部HTML標(biāo)簽,輸出:Linux Apache Mysql PHP
echo strip_tags($str,""); //輸出LinuxApache Mysql PHP
echo strip_tags($str,""); //輸出Linux Apache Mysql PHP
?>
四、其他字符串格式化函數(shù)
字符串的格式化處理函數(shù)還有很多,只要是想得到所需要格式化的字符串,都可以調(diào)用PHP中提供的系統(tǒng)函數(shù)處理,很少需要自己定義字符串格式化函數(shù)。
①函數(shù)strrev()
該函數(shù)的作用是將輸入的字符串反轉(zhuǎn),只提供一個要處理的字符串作為參數(shù),返回翻轉(zhuǎn)后的字符串。如下所示:
復(fù)制代碼 代碼如下:
echo strrev("http://www.lampbrother.net"); //反轉(zhuǎn)后輸出:ten.rehtorbpmal.www//:ptth
?>
②函數(shù)number_format()
number_format()函數(shù)通過千位分組來格式化數(shù)字。該函數(shù)如下所示:
復(fù)制代碼 代碼如下:
string number_format(float number[,int decimals[,string dec_point,string thousands_sep]])
復(fù)制代碼 代碼如下:
$number = 123456789;
echo number_format($number);????? //輸出:123,456,789千位分隔的字符串
echo number_format($number,2);?????? //輸出:123,456,789.00小數(shù)點后保留兩位小數(shù)
echo number_format($number,2,",",".");?????? //輸出123.456.789,00千位使用(.)分隔了,并保留兩位小數(shù)
?>
③函數(shù)md5()
隨著互聯(lián)網(wǎng)的普及,黑客攻擊已成為網(wǎng)絡(luò)管理者的心病。有統(tǒng)計數(shù)據(jù)表明70%的攻擊來自內(nèi)部,因此必須采取相應(yīng)的防范措施來扼制系統(tǒng)內(nèi)部的攻擊。防止內(nèi)部攻擊的重要性還在于內(nèi)部人員對數(shù)據(jù)的存儲位置、信息重要性非常了解,這使得內(nèi)部攻擊更容易奏效。攻擊者盜用合法用戶的身份信息,以仿冒的身份與他人進(jìn)行通信。所以在用戶注冊時應(yīng)該先將密碼加密后再添加到數(shù)據(jù)庫中,這樣就可以防止內(nèi)部攻擊者直接查詢數(shù)據(jù)庫中的授權(quán)表,盜用合法用戶的身份信息。
md5()函數(shù)的作用就是將一個字符串進(jìn)行MD5算法加密,默認(rèn)返回一個32位的十六進(jìn)制字符串。
復(fù)制代碼 代碼如下:
$password = "lampbrother";
echo md5($password)."
";
?
//將輸入的密碼和數(shù)據(jù)庫保存的匹配
if(md5($password) == '5f1ba7d4b4bf96fb8e7ae52fc6297aee'){
echo "密碼一致,登錄成功";
}
?>
在PHP中提供了一個對文件進(jìn)行MD5加密的函數(shù)md5_file(),使用的方式和md5()函數(shù)相似。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
