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

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)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
