Summary of commonly used string formatting functions in PHP, php functions_PHP tutorial

WBOY
Release: 2016-07-13 10:13:37
Original
859 people have browsed it

A summary of commonly used string formatting functions in PHP, php functions

String formatting is to process the string into a specific format. Usually the data submitted by users to the server from the form is in the form of strings. In order to achieve the desired output effect, these strings need to be processed in a certain format before use. The commonly seen string formatting functions are as shown below:

Note: Most of the strings processed by the string functions provided in PHP do not modify the original string, but return a formatted new string.

1. Remove spaces and string padding functions

A space is also a valid character and occupies a position in the string. When users enter data in a form, they often unintentionally enter extra meaningless spaces. Therefore, when the PHP script receives the data processed through the form, the first thing it processes is the extra spaces in the string, or other meaningless symbols. This work can be done in PHP through the ltrim(), rtrim() and trim() functions. The syntax format of these three functions is the same, but their functions are different. Their syntax format is as follows:

Copy code The code is as follows:

string ltrim(string str[,string charlist]) //Remove spaces or other predefined characters from the left side of the string
string rtrim(string str[,string charlist]) //Remove blank characters or other predefined characters from the right side of the string
string trim(string str[,string charlist]) //Remove blank characters or other predefined characters from both ends of the string

These three functions are used to remove whitespace characters or other predefined characters from the left, right, and both ends of a string respectively. The processed results will be returned in the form of new strings and will not be modified on the original strings. The first parameter str is the string to be processed and is required. The second parameter charlist is a filter string, used to specify the special symbols you want to remove. This parameter is optional. If you do not specify a filter string, the following characters will be removed by default.

★"":space
★”0”:NULL
★"t":tab
★”n”:new line
★"r": Enter

In addition, you can also use the ".." symbol to specify a range that needs to be removed, such as "0..9" or "a..z" to remove numbers and small letters in the ASCII code value. Their usage code is as follows:

Copy code The code is as follows:

$str = "123 This is a test ..."; //Declare a test string, starting with a number on the left and an ellipsis
on the right echo ltrim($str,"0..9"); //Filter out the numbers on the left side of the string and output This is a test...
echo rtrim($str,".") //Filter out all "." on the right side of the string, output: 123 This is a test
echo trim ($str, "0..9 A..Z ."); //Filter out the numbers, uppercase letters and "." at both ends of the string, output: his is a test
?>

Not only can you filter out the content in the string as needed, you can also use the str_pad() function to fill the string as needed. It can be used to protect some sensitive information, such as data pairing and arrangement. The prototype of its function is as follows:

Copy code The code is as follows:

string str_pad(string input,int pad_length[,string pad_string[,int pad_type]])

This function has 4 parameters, the first parameter specifies the string to be processed. The second parameter gives the length of the processed string. If the value is less than the length of the original string, no operation is performed. The third parameter specifies the string used for padding. It is an optional parameter. If not specified, spaces will be used for padding by default. The last parameter specifies the direction of padding, which has three optional values: STR_PAD_BOTH, STR_PAD_LEFT and STR_PAD_RIGHT, which represent padding at both ends, left and right of the string respectively. Also an optional parameter, if not specified, the default value is STR_PAD_RIGHT. The usage code of function str_pad() is as follows:
Copy code The code is as follows:

$str = "LAMP";
echo str_pad($str,10); //The specified length is 10, and by default, spaces are used to fill "LAMP" on the right
echo str_pad($str,10,"-="STR_PAD_LEFT); //Specify the length as 10, and specify "-=-=-=LAMP" to be padded on the left
echo str_pad($str,10,"_"STR_PAD_BOTH); //Specify the length as 10, and specify "___LAMP___" to be padded on the left
?>

2. String case conversion

There are 4 string case conversion functions provided in PHP. They all have only one optional parameter, which is to pass in the string to be converted. You can use these functions directly to complete the case conversion operation. The function strtoupper() is used to convert all the given strings into uppercase letters; the function strtolower() is used to convert all the given strings into lowercase letters; the function ucfirst() is used to convert all the characters in the given string The first letter is converted to uppercase, while the remaining characters remain unchanged; the function ucwords() is used to convert the first letter of all words separated by spaces in the given string to uppercase. The following program is the usage code of these functions, as shown below:

Copy code The code is as follows:

$lamp = "lamp is composed of Linux, Apache, MySQL and PHP";
echo strtolower($lamp); //Output: lamp is composed of linux, apache, mysql and php
echo strtoupper($lamp); //Output: LAMP IS CONPOSED OF LINUX, APACHE, MYSQL AND PHP
echo ucfirst($lamp); //Output: Lamp is composed of Linux, Apache, MySQL and PHP
echo ucwords($lamp); //Output: Lamp Is Composed Of Linux, Apache, MySQL And PHP
?>

These functions only work as described in their descriptions. To ensure that the first letter of a string is an uppercase letter and the rest are lowercase letters, you need to use a matching method. As shown below:
Copy code The code is as follows:

$lamp = "lamp is composed of Linux, Apache, MySQL and PHP";
echo ucfirst(strtolower($lamp)); //Output: Lamp is composed of linux, apache, mysql and php
?>

3. String formatting related to HTML tags

HTML input forms and resources attached to URLs are ways for users to submit data to the server. If not handled well, they may become entry points for hackers to attack the server. For example, when a user publishes an article, if the article contains some HTML formatting tags or JavaScript page redirection code, the layout of the page will definitely change if it is directly output and displayed. Because these codes are sent to the browser, the browser interprets them as valid codes. Therefore, in PHP scripts, the data content submitted by the user must be processed first. PHP provides us with a very comprehensive range of HTML-related string formatting functions, which can effectively control the output of HTML text.

①Function nl2br()

The string "
" output in the browser marks a newline, and many people are accustomed to using "n" as the newline symbol, but the browser does not recognize the newline character of this string. Even if there are multiple lines of text, only this line will be displayed in the browser. The nl2br() function inserts the HTML newline character "
" before each new line "n" in the string. The usage of this function is as follows:

Copy code The code is as follows:

echo nl2br("One line.nAnother line."); //Add "
" mark before "n"
/*Output the following two lines of results
One line.

Another line.
*/
?>

②Function htmlspecialchars()

If you do not want the browser to parse HTML tags directly, you need to convert the special characters in the HTML tags into HTML entities. For example, convert "<" to "<" and ">" to ">". In this way, the HTML tag browser will not parse it, but will output the HTML text in the browser as it is. The htmlspecialchars() function provided in PHP can convert some predefined strings into HTML entities. This function is used to prevent user-supplied text from containing HTML tags, such as bulletin boards or guest message boards. The following characters can be converted by this function:

★ "&" (ampere) is converted to "&".
★""" (double quotation mark) is converted to """.
★"'" (single quote) is converted to "'".
★"<" (less than) is converted to "<".
★">" (greater than) is converted to ">".

The prototype of this function is as follows:

Copy code The code is as follows:

string htmlspecialchars(string string [,int quote_style[,string charset]])

The first parameter in this function is a string with HTML tags to be processed. The second parameter is used to determine how quotation marks are converted. The default value is ENT_COMPAT, which will only convert double quotes and retain single quotes; ENT_QUOTES, which will convert both types of quotes; and ENT_NOQUOTES, which will not convert the quotes. The third parameter is used to specify the character set of the string being processed. The default character set is "ISO88511-1".

Copy code The code is as follows:



$str = "WebServer: & 'Linux' & 'Apache'"; //String with HTML tags and single quotes
echo htmlspecialchars($str,ENT_COMPAT); //Convert HTML tags and convert double quotes
echo "
n";
echo htmlspecialchars($str,ENT_QUOTES); //Convert HTML tags and convert two kinds of quotes
echo "
n";
echo htmlspecialchars($str,ENT_NOQUOTES); //Convert HTML tags and unquote conversion
echo "
n";
?>


Output results in browser

Copy code The code is as follows:

WebServer: & ‘Linux’ & ‘Apache’
WebServer: & ‘Linux’ & ‘Apache’
WebServer: & ‘Linux’ & ‘Apache’

If you view the source code in a browser, you will see the following result:
Copy code The code is as follows:



WebServer:&'Linux'&'Apache'
//Single quotes are not converted
WebServer:&'Linux'&'Apache'

WebServer:&'Linux'&'Apache' //Single quotes are not converted


The htmlentities() function is also provided in PHP, which can convert all non-ASCII characters into corresponding entity codes. This function has the same syntax format as the htmlspecialchars() function, which can escape more HTML characters. The following code is an example of using the htmlentities() function:

Copy code The code is as follows:

$str = "A 'quote' isbold";
//Output&0qrave;»¸ö 'quote' ÊÇ <:b>bold
echo htmlentities($str);
//Output: a 'quote' is bold
echo htmlentities($str,ENT_QUOTES,gb2312);
?>

When processing the data submitted in the form, not only the HTML markup symbols and some special characters must be converted into HTML entities through the functions introduced earlier, but the quotation marks must also be processed. Because characters such as "'", """ and "" in the submitted form data will be automatically added with a slash "". This is due to the option magic_quotes_gpc in the PHP configuration file php.ini. The default is If it is turned on, use the function stripslashes() to remove the backslash. If it is not processed, the database may mistake it as a control symbol and cause an error. There is only one function stripslashes(). The processed string is used as a parameter and the processed string is returned. The htmlspecialchars() function and the stripslashes() function are usually used to jointly process the data submitted in the form.

The function of the function stripslashes() is to remove the backslash "". If there are two consecutive backslashes, only one will be removed. Corresponding to it is another function addslashes(). As the function name implies, it will add necessary backslashes before "'", """, "" and NULL characters.

The function htmlspecialchars() converts the mark symbols in the function HTML into the corresponding HTML entities. Sometimes it is also necessary to directly delete the HTML tags input by the user. The strip_tags() function provided in PHP can delete all HTML tags in the string by default, and can also selectively delete some HTML tags. Such as bulletin boards or guest message boards, it is quite necessary to have applications in this area. For example, when users publish articles in a forum, they can reserve some HTML tags that can change font size, color, bold and italics, etc., and delete some HTML tags that have an impact on page layout. The prototype of the function strip_tags() is as follows:

Copy code The code is as follows:

string strip_tags(string str[,string allowable_tags]); //Delete HTML tag function

This function has two parameters. The first parameter provides the string to be processed. The second parameter is an optional list of HTML tags. The HTML tags placed in the list will be retained, and all others will be deleted. . All HTML tags are deleted by default. The following program uses the scope of this function as follows:
Copy code The code is as follows:

$str = "Linux Apache Mysql PHP";
echo strip_tags($str); //All HTML tags are deleted, output: Linux Apache Mysql PHP
echo strip_tags($str,""); //OutputLinuxApache Mysql PHP
echo strip_tags($str,""); //Output Linux Apache Mysql PHP< /b>
?>

4. Other string formatting functions

There are many string formatting functions. As long as you want to get the string that needs to be formatted, you can call the system functions provided in PHP. You rarely need to define your own string formatting function.

①Function strrev()

The function of this function is to reverse the input string, provide only a string to be processed as a parameter, and return the reversed string. As shown below:

Copy code The code is as follows:

echo strrev("http://www.lampbrother.net"); //Output after reverse: ten.rehtorbpmal.www//:ptth
?>

②Function number_format()

The number_format() function formats numbers by thousands grouping. The function looks like this:

Copy code The code is as follows:

string number_format(float number[,int decimals[,string dec_point,string thousands_sep]])

Copy code The code is as follows:

$number = 123456789;
echo number_format($number); //Output: 123,456,789 thousand-digit separated string
echo number_format($number,2); //Output: 123,456,789.00 with two decimal places after the decimal point
echo number_format($number,2,",","."); //Output 123.456.789, the thousand digits are separated by (.) and retain two decimal places
?>

③Function md5()

With the popularity of the Internet, hacker attacks have become a concern for network administrators. Statistics show that 70% of attacks come from within, so corresponding preventive measures must be taken to curb attacks within the system. The importance of preventing insider attacks also lies in the fact that insiders have a good understanding of where data is stored and the importance of the information, which makes insider attacks more likely to be effective. Attackers steal the identity information of legitimate users and communicate with others under fake identities. Therefore, when a user registers, the password should be encrypted before being added to the database. This can prevent internal attackers from directly querying the authorization table in the database and stealing the identity information of legitimate users.

The md5() function is to encrypt a string with the MD5 algorithm and returns a 32-bit hexadecimal string by default.

Copy code The code is as follows:

$password = "lampbrother";
echo md5($password)."
";

//Match the entered password with the one saved in the database
if(md5($password) == '5f1ba7d4b4bf96fb8e7ae52fc6297aee'){
echo "The passwords are consistent and the login is successful";
}
?>

In PHP, a function md5_file() is provided for MD5 encryption of files. The method of use is similar to the md5() function.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/914060.htmlTechArticleA summary of commonly used string formatting functions in PHP. The formatting of PHP function strings is to process the string as a specific format. Usually the data submitted by the user to the server from the form is...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template