Summary of commonly used string formatting functions in PHP

Source: Internet
Author: User
Tags float number rtrim

Note: The string functions that are provided in PHP are mostly not modified on the original string, but instead return a new formatted string.

One, take out space and string fill function

A space is also a valid character and occupies a position in the string. When users enter data in a form, they often inadvertently enter some meaningless spaces. So when the PHP script receives the data processed through the form, the first thing is to deal with the extra spaces in the string, or some other meaningless symbol. This work can be done in PHP via the LTrim (), RTrim (), and trim () functions. The syntax format of these three functions is the same, but the functions are different. Their syntax format 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])//Remove white-space characters or other predefined characters from the right side of the string

String Trim (String str[,string charlist])//Remove white space characters or other predefined characters from both ends of a string

These three functions are used to remove white-space characters or other predefined characters from the left, right, and ends of a string, respectively. The processed results are returned as a new string and are not modified on the original string. Where the first parameter, str, is the string to be processed, the required option. The second parameter, charlist, is a filter string that specifies the special symbol you want to remove, which is optional. If you do not specify a filter string, the following characters are removed by default.

★ "": Space
★ "0\": NULL
★ "\ T": Tab
★ "\ n": New Line
★ "\ r": Enter

You can also use the ".." The symbol specifies a range that needs to be removed, such as "0..9" or "A." Z "means removing the numbers and small letters from the ASCII value. Their code of use is as follows:

<?php
$STR = "123" is a test ... "; Declares a test string, the left side is a number, and the right side is an ellipsis
Echo LTrim ($str, "0..9"); Filter out the number to the left of the string, 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 and uppercase letters at both ends of the string and ".", Output: he is a test
?>

Not only can you filter out the contents of the string as required, but you can also use the Str_pad () function to fill the string as required. can be used to protect sensitive information, such as the alignment and arrangement of data. The prototype of its function is as follows:

String Str_pad (String Input,int pad_length[,string pad_string[,int Pad_type])

The function has 4 parameters, and the first parameter indicates the string to be processed. The second argument is given the length of the string after processing, and if the value is less than the length of the original string, no action is made. The third parameter specifies the string to fill with, which is an optional parameter and, if not specified, uses a space to fill by default. The last parameter specifies the direction of the fill, which has three optional values: Str_pad_both, Str_pad_left, and Str_pad_right, respectively, representing the padding at both ends of the string, left and right. is also an optional parameter, if not specified, the default value is Str_pad_right. The usage code for the function Str_pad () is as follows:

<?php
$str = "LAMP";
Echo Str_pad ($STR, 10); Specify a length of 10, using a space by default to fill "LAMP" on the right
Echo Str_pad ($str, ten, "-=" str_pad_left); Specify a length of 10, specify to fill "-=-=-=lamp" on the Left
Echo Str_pad ($str, Ten, "_" Str_pad_both); Specify a length of 10, specify to fill "___lamp___" on the Left
?>

Second, string-case conversion

There are 4 string-case conversion functions in PHP that have only one optional argument, the string passed in to be converted. You can use these functions directly to complete the case conversion operation. The function Strtoupper () is used to convert the given string all to uppercase, the function strtolower () is used to convert the given string all to lowercase letters, the function Ucfirst () is used to convert the first letter in the given string to uppercase, the remaining characters are unchanged The function ucwords () is used to convert the first letter of a given string of words separated by spaces into uppercase. The following program is the use code for these functions, 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 them, and to make sure that the first letter of a string is uppercase, and the rest is lowercase, you need to use it in a consistent manner. As shown below:

<?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
?>

Third, and HTML tags related to the formatting of the string

HTML input forms and URLs on the additional resources is the way users submit data to the server, if not well handled, it is possible to become a hacker attack server portal. For example, when a user publishes an article, if the article contains some HTML formatting tags or JavaScript page steering code, the direct output display will definitely use the page layout changes. Because the code is sent to the browser, the browser interprets it as valid code. So in the PHP script, the user submits the content of the data must be processed first. In PHP we provide a very comprehensive HTML-related string formatting function, you can effectively control the output of HTML text.

① function nl2br ()

The string "<br>" is printed in the browser, and many people are accustomed to using "\ n" as a newline symbol, but the line break of the string is not recognized in the browser. Even if there is more than one line of text, only this line is displayed in the browser. The NL2BR () function is to insert the HTML line break "<br/>" before each new line "\ n" in the string. The use of this function is as follows:

<?php
Echo nl2br ("One line.\nanother line."); Add the "<br/>" tag before "\ n"
/* Output The following two rows of results
One line.<br/>
Another line.
*/
?>

② function Htmlspecialchars ()

If you do not want the browser to parse HTML markup directly, you need to convert the special characters in the HTML markup into HTML entities. For example, convert "<" to "<" and ">" to ">". In this way, the HTML markup browser does not parse, but instead prints the HTML text as it is in the browser. The Htmlspecialchars () function provided in PHP allows you to convert some of the predefined strings into HTML entities. This function includes HTML tags in the text provided by the prevention user, such as the application of a bulletin board or a guest message pad. The following are the characters that the function can convert:

★ "&" (and number) converted to "&".
★ "" "(double quotation marks) to" ".
★ "'" (single quote) converted to "'".
★ "<" (less than) converted to "<".
★ ">" (greater than) conversion to ">".

The function is prototyped as follows:

String Htmlspecialchars (String string [, int quote_style[,string CharSet])

The first parameter in the function is a string with an HTML tag to be processed. The second parameter is used to determine how the quotation marks are converted. The default value, Ent_compat, converts only double quotes, while the single quotation marks are preserved, and ent_quotes converts both quotes, and Ent_noquotes does not convert the quotation marks. The third parameter specifies the character set of the string being processed, and the default character set is "Iso88511-1".

< body>
< PHP
$str = "<B>WebServer:</B> & ' Linux ' & ' Apache '"; Strings that will have HTML tags and single quotes
Echo Htmlspecialchars ($str, Ent_compat); Convert HTML tags and convert double quotes
echo "<br>\n";
Echo Htmlspecialchars ($str, ent_quotes); Convert HTML tags and convert two types of quotation marks
echo "<br>\n";
Echo Htmlspecialchars ($str, ent_noquotes); Convert HTML tags and do not quote conversions
echo "<br>\n";
?>
</body>

Output results in the browser

<B>WebServer:</B> & ' Linux ' & ' Apache '
< b>webserver:</b> & ' Linux ' & ' Apache '
< b>webserver:</b> & ' Linux ' & ' Apache '

If you view the source code in your browser, you will see the following result:

< body>
< b>webserver:</b>& ' Linux ' & ' Apache ' <br>//No conversion single quotes
<B>WebServer:</B>& ' Linux ' & ' Apache ' <br>
< b>webserver:</b>& ' Linux ' & ' Apache '//No conversion single quotes
</body>

The Htmlentities () function is also available in PHP to convert all non-ASCII characters to the corresponding entity code. This function is consistent with the syntax format of the Htmlspecialchars () function, which can escape more HTML characters. The following code is an example of the use of the Htmlentities () function:

<?php
$str = "A ' quote ' is <b>bold</b>";
Output &0qrave;» ¸ö ' quote ' êç<b> <:b>bold</b>
echo htmlentities ($STR);
Output: A ' quote ' is <b>bold</b>
Echo htmlentities ($str, ent_quotes,gb2312);
?>

When working with data submitted in a form, you need to handle not only the markup symbols and some special characters of the HTML, but also the quotation marks, as described in the previous function. Because the "'", "" "and" \ "characters in the submitted form data are automatically preceded by a slash" \ ". This is due to the option MAGIC_QUOTES_GPC in PHP configuration file php.ini, which is turned on by default, and if you do not close it, use the function stripslashes () to remove the backslash. When you save data to a database without processing, you may be mistaken for a control symbol by the database. The function stripslashes () has only one processed string as a parameter, returning the processed string. The data submitted in the form is typically processed in a way that uses the Htmlspecialchars () function in combination with the Stripslashes () function.

function stripslashes () function is to remove the backslash "\", if there are two consecutive backslashes, then only one is removed. It corresponds to another function, addslashes (), which, as the function name implies, adds the necessary backslashes before "'", "" "," \ ", and the null character.

The function Htmlspecialchars () is necessary to convert the marker symbol in the function HTML to the corresponding HTML entity, and sometimes to delete the user input HTML tag directly. The Strip_tags () function provided in PHP removes all HTML tags from the string by default, and optionally deletes some HTML tags. such as the bulletin board or guest message boards, this application is quite necessary. For example, when you publish an article in a forum, you can reserve some HTML tags that can change font size, color, bold, italic, and so on, while deleting some HTML tags that affect the layout of the page. The prototype of the function Strip_tags () is as follows:

String Strip_tags (String str[,string allowable_tags]); Remove the tag function for HTML

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

<?php
$str = "<font color= ' red ' size=7>linux</font> <i>Apache</i> <u>Mysql</u> <b >PHP</b> ";
echo Strip_tags ($STR); Removed all HTML tags, output: Linux Apache Mysql PHP
Echo strip_tags ($str, "<font>"); Output <font color= ' red ' size=7>linux</font>apache Mysql PHP
Echo strip_tags ($str, "<b><u><i>"); Output Linux <i>Apache</i> <u>Mysql</u> <b>PHP</b>
?>

Iv. other string formatting functions

There are many more formatting functions for strings, as long as you want to get the formatted string, you can call the system functions provided in PHP, you rarely need to define the string format function.

① function Strrev ()

The function is to invert the input string, providing only one string to process as a parameter, returning the flipped string. As shown below:

<?php
Echo Strrev ("http://www.baidu.net"); Inverted output: ten.udiab.www//:p TTH
?>

② function Number_format ()

The Number_format () function formats numbers by using thousands of groupings. The function is as follows:

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

<?php
$number = 123456789;
echo Number_format ($number); Output: 123,456,789 thousand-delimited string
Echo Number_format ($number, 2); Output: 123,456,789.00 two decimal places after decimal point
Echo Number_format ($number, 2, ",", "."); Output 123.456.789,00 thousand use (.) Separated, and reserved two decimal places
?>

③ function MD5 ()

With the popularization of Internet, hacker attack has become the heart of network manager. There are statistics that show that 70% of attacks come from the inside, so appropriate precautions must be taken to curb attacks within the system. The importance of preventing insider attacks is also that insiders understand the location of the data and the importance of the information, making it easier for internal attacks to work. An attacker steals identity information from a legitimate user and communicates with others in a counterfeit identity. Therefore, when the user registers, the password should be encrypted and then added to the database, which will prevent the internal attacker to directly query the database authorization table, misappropriation of legitimate user identity information.

The purpose of the MD5 () function is to encrypt a string with the MD5 algorithm, which returns a 32-bit hexadecimal string by default.

<?php
$password = "Lampbrother";
echo MD5 ($password). " <br> ";

Match the password you entered and save the database
if (MD5 ($password) = = ' 5f1ba7d4b4bf96fb8e7ae52fc6297aee ') {
echo "Password consistent, login success";
}
?>

A function md5_file () that MD5 encrypted files is provided in PHP in a way that is similar to the MD5 () function.

Summary of commonly used string formatting functions in PHP

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.