Summary of common string formatting functions in PHP

Source: Internet
Author: User
Tags float number
This article mainly introduces the summary of common string formatting functions in PHP. the functions described in this article are frequently used on the WEB, for example, functions such as space filling and string filling, case-sensitive conversion of strings, and string formatting related to HTML tags are extracted, for more information about how to format strings, see format strings. Generally, the data submitted to the server from the form is in the string format. to achieve the expected output, you need to process these strings in a certain format before using them. Shows the common string formatting functions:

Note: most of the strings processed by string functions provided in PHP are not modified on the original string, but return a formatted new string.

1. remove spaces and strings to fill the function

A space is also a valid character, which occupies a position in the string. When users input data in a form, they often accidentally enter meaningless spaces. Therefore, when the PHP script receives data processed through a form, it first processes unnecessary spaces in the string or other meaningless symbols. In PHP, you can use the ltrim (), rtrim (), and trim () functions to do this. The syntax format of the three functions is the same, but the functions are different. Their syntax format is as follows:

The code is as follows:


String ltrim (string str [, string charlist]) // remove spaces or other predefined characters from the left of the string
String rtrim (string str [, string charlist]) // removes white spaces or other predefined characters from the right of the string
String trim (string str [, string charlist]) // removes white spaces or other predefined characters from both ends of the string.


These three functions are used to delete white spaces or other predefined characters from the left, right, and both ends of the string. The processed results will be returned in the form of a new string and will not be modified on the original string. The first parameter str is a string to be processed and is required. The second charlist parameter is a filter string used to specify the special symbols to be removed. this parameter is optional. If no filter string is specified, the following characters are removed by default.

★"": Space
★"0 \": NULL
★"": TAB
★": New Line
★": Enter

You can also use "symbol specifies a range to be removed, for example," 0 .. 9 "or" .. z "indicates removing digits and small letters from ASCII code values. Their usage code is as follows:

The code is as follows:


<? Php
$ Str = "123 This is a test..."; // declare a test string starting with a number on the left and a ellipsis on the right
Echo ltrim ($ str, "0 .. 9"); // filter out the number on the left of the string and output This is a test...
Echo rtrim ($ str, ".") // filter out all "." on the right of the string, and output: 123 This is a test
Echo trim ($ str, "0 .. 9 .. z. "); // filter out the numbers and uppercase letters at both ends of the string and". ", output: his is a test
?>

Not only can the content in the string be filtered out as needed, but also the str_pad () function can be used to fill the string as needed. It can be used to protect sensitive information, such as data pairs and sorting. The function prototype is as follows:

The code is as follows:


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


This function has four parameters. The first parameter specifies the string to be processed. The second parameter is the length of the processed string. if the value is smaller than the length of the original string, no operation is performed. The third parameter specifies the string used for filling. it is an optional parameter. if not specified, spaces are used by default. The last parameter specifies the fill direction. It has three optional values: STR_PAD_BOTH, STR_PAD_LEFT, and STR_PAD_RIGHT, which indicate filling at both ends, left, and right of the string respectively. It is also an optional parameter. if not specified, the default value is STR_PAD_RIGHT. The code for using the str_pad () function is as follows:

The code is as follows:


<? Php
$ Str = "LAMP ";
Echo str_pad ($ str, 10); // specify the length to 10. by default, "LAMP" is filled with spaces on the right"
Echo str_pad ($ str, 10, "-=" STR_PAD_LEFT); // specify the length to 10 and fill "-= LAMP" on the left"
Echo str_pad ($ str, 10, "_" STR_PAD_BOTH); // specify the length to 10 and fill "___ LAMP ___" on the left ___"
?>

II. string case-insensitive conversion

Four String case-sensitivity conversion functions are provided in PHP. they all have only one optional parameter, that is, the string to be converted. You can directly use these functions to perform case-insensitive conversion. The strtoupper () function is used to convert all the given strings to uppercase letters. the strtolower () function is used to convert all the given strings to lowercase letters. the ucfirst () function () converts the first letter of a given string to uppercase, and the rest of the characters remain unchanged. ucwords () is used to convert the first letter of all words in a given string separated by spaces to uppercase. The following code is used for these functions:

The code is as follows:


<? Php
$ 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 in the way they describe. to ensure that the first letter of a string is an upper-case letter, while the rest are lower-case letters, you need to use the appropriate method. As follows:

The code is as follows:


<? Php
$ 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. HTML tag-related string formatting

Adding resources to HTML input forms and URLs is a way for users to submit data to the server. if the data cannot be well processed, it may become the entry point for hackers to attack the server. For example, when a user publishes an article, if the article contains code such as HTML format tags or JavaScript page turns, the layout of the page will be changed if the code is output directly. Because the code is sent to the browser, the browser will explain it according to the valid code. Therefore, in the PHP script, the data content submitted by the user must be processed first. In PHP, we provide comprehensive HTML-related string formatting functions to effectively control HTML text output.

① Function nl2br ()

The string"
"Mark the line feed, and many people use" "as the line feed symbol, but the browser does not recognize the line break of this string. This line is only displayed in the browser even if there are multiple lines of text. The nl2br () function inserts an HTML line break before each new line "" in the string.
". The function is used as follows:

The code is as follows:


<? Php
Echo nl2br ("One line. \ nAnother line."); // add"
Mark
/* Output the following two rows.
One line.

Another line.
*/
?>

② Function htmlspecialchars ()

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

★"&" (And) is converted to "&".
★"" (Double quotation marks) to ".
★''(Single quotes) to''.
★"<" (Less than) to "<".
★">" (Greater than) to "> ".

The function is prototype as follows:

The code is as follows:


String htmlspecialchars (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 the conversion method of quotation marks. The default value is ENT_COMPAT. only double quotation marks are converted, while single quotation marks are retained. ENT_QUOTES converts both quotation marks. ENT_NOQUOTES does not convert the quotation marks. The third parameter is used to specify the character set of the string to be processed. the default character set is ISO88511-1 ".

The code is as follows:




<? Php
$ Str ="WebServer:& 'Linux '& 'Apache' "; // strings with HTML tags and single quotes
Echo htmlspecialchars ($ str, ENT_COMPAT); // Convert HTML tags and double quotation marks
Echo"
\ N ";
Echo htmlspecialchars ($ str, ENT_QUOTES); // Convert two quotation marks: HTML tag and conversion.
Echo"
\ N ";
Echo htmlspecialchars ($ str, ENT_NOQUOTES); // Convert HTML tags and do not convert quotation marks
Echo"
\ N ";
?>


Output results in the browser

The code is as follows:


WebServer:& 'Linux '& 'Apache'
WebServer:& 'Linux '& 'Apache'
WebServer:& 'Linux '& 'Apache'


If you view the source code in the browser, the following result is displayed:

The code is as follows:




WebServer:& 'Linux '& 'Apache'
// No conversion single quotes
WebServer:& 'Linux '& 'Apache'

WebServer:& 'Linux '& 'Apache' // no conversion single quotes


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

The code is as follows:


<? Php
$ Str = "A 'quote' isBold";
// Output & 0 qrave;» ö ö'quote' Ç<: B> bold
Echo htmlentities ($ str );
// Output: A 'quote' isBold
Echo htmlentities ($ str, ENT_QUOTES, gb2312 );
?>

When processing data submitted in a form, you must not only convert HTML markup symbols and some special characters into HTML entities through the functions described earlier, but also process quotation marks. This is because a forward slash ("") is automatically added before the "'", ", and" "characters in the submitted form data. This is because the magic_quotes_gpc option in the PHP configuration file php. ini is enabled by default. if it is not disabled, delete the backslash using the stripslashes () function. If the data is not processed, it may be mistakenly treated as a control symbol by the database when the data is saved to the database. The stripslashes () function has only one string to be processed as a parameter and returns the processed string. Generally, the htmlspecialchars () function and stripslashes () function are combined to process the data submitted in the form.

The function of stripslashes () is to remove the backslash "". if two consecutive backlash lines exist, only one is removed. It corresponds to another function addslashes (), as the function name implies, it will add the necessary backslash before "'", "," ", and NULL characters.

The htmlspecialchars () function converts the markup symbol in the function HTML to the corresponding HTML entity. sometimes it is necessary to directly delete the HTML tag entered by the user. By default, the strip_tags () function provided in PHP can delete all HTML tags in the string or selectively delete some HTML tags. Such as the bulletin board or guest message board, it is quite necessary to have such applications. For example, when publishing an article in a forum, you can reserve HTML tags that can change the font size, color, bold, and italic, and delete HTML tags that affect the page layout. The prototype of the strip_tags () function is as follows:

The code is as follows:


String strip_tags (string str [, string allowable_tags]); // deletes the HTML tag function.


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

The code is as follows:


<? Php
$ Str = "LinuxApache Mysql PHP";
Echo strip_tags ($ str); // All HTML tags are deleted. output: Linux Apache Mysql PHP
Echo strip_tags ($ str, ""); // output LinuxApache Mysql PHP
Echo strip_tags ($ str ,""); // Output LinuxApache Mysql PHP
?>

IV. other string formatting functions

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

① Function strrev ()

This function is used to reverse the input string. only one string to be processed is provided as a parameter and the string to be processed is returned. As follows:

The code is as follows:


<? Php
Echo strrev ("http://www.lampbrother.net"); // output after reversal: ten. rehtorbpmal. www //: ptth
?>

② Function number_format ()

The number_format () function uses a thousand-bit grouping to format numbers. This function is as follows:

The code is as follows:


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

The code is as follows:


<? Php
$ Number = 123456789;
Echo number_format ($ number); // output: 123,456,789-bit string
Echo number_format ($ number, 2); // output: retain two decimal places after 123,456,789.00
Echo number_format ($ number, 2, "."); // output 123.456.789, 00 kilobytes separated by (.), and retain two decimal places
?>

③ Function md5 ()

With the popularity of the Internet, hacker attacks have become the heart of network managers. Statistics show that 70% of attacks come from the inside, so we must take corresponding preventive measures to curb internal attacks. The importance of preventing internal attacks also lies in the fact that internal personnel are very familiar with the data storage location and information importance, which makes internal attacks more effective. Attackers steal the identity information of legitimate users and communicate with others as counterfeits. Therefore, during user registration, the password should be encrypted before being added to the database. This prevents internal attackers from directly querying the authorization table in the database and stealing the identity information of legal users.

The md5 () function is used to encrypt a string using the MD5 algorithm. by default, a 32-bit hexadecimal string is returned.

The code is as follows:


<? Php
$ Password = "lampbrother ";
Echo md5 ($ password )."
";

// Match the entered password with the saved database
If (md5 ($ password) = '5f1ba7d4b4bf96fb8e7ae52fc6297aee '){
Echo "consistent password, logon successful ";
}
?>

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.