Common string formatting Functions in PHP summary _php tips

Source: Internet
Author: User
Tags float number lowercase md5 md5 encryption php script rtrim

The format of a string is the processing of a string into a particular format. Usually the data that the user gives to the server from the form is in the form of strings, and in order to achieve the desired output, the strings need to be processed in a certain format before they are used. The string formatting functions that are often seen are shown in the following illustration:

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

First, remove space and string filling 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 meaningless spaces. So when a PHP script receives data processed through a form, it first deals with extra spaces in the string, or other meaningless symbols. You can do this by using the LTrim (), RTrim () and trim () functions in PHP. The syntax format of these three functions is the same, but the effect is different. Their syntax format is as follows:

Copy Code code 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 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 the string

These three functions are used to remove whitespace characters or other predefined characters from the left, right, and both ends of the string, respectively. The processed results are returned as a new string and are not modified on the original string. The first parameter, str, is the string to be processed, which is required. The second parameter, charlist, is a filter string that specifies the special symbol that 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

In addition, you can use the ".." The symbol specifies a range that needs to be removed, such as "0..9" or "a". Z "means to remove numbers and small letters from ASCII values. Their code of use is as follows:

Copy Code code as follows:

<?php
$STR = "123 This is a test ..."; Declares a test string, starts with a number on the left, and an ellipsis on the right
Echo LTrim ($str, "0..9"); Filter out the digits to the left of the string, and the output 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. " ); Filters 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 a string as needed, but you can also use the Str_pad () function to fill strings as needed. Can be used for protection of sensitive information, such as the alignment and alignment of data. The prototype of its function is as follows:

Copy Code code 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, which is an optional parameter and, if not specified, by using a space to fill it. 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 ends of the string, left, and right to fill. is also an optional parameter and, if not specified, the default value is Str_pad_right. The use code for the function Str_pad () is as follows:
Copy Code code as follows:

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

Ii. Conversion of string capitalization

In PHP, 4 string-case conversion functions are available, each with only one optional parameter, that is, passing in the string to be converted. You can use these functions directly to complete case conversion operations. function Strtoupper () is used to convert all the given strings to uppercase letters; the function strtolower () is used to convert all the given strings to lowercase letters; the function Ucfirst () is used to convert the first letter in the given string to uppercase and the remaining characters unchanged The function ucwords () is used to convert the first letter of all the words in a given string to uppercase. The following program is the code for using these functions, as follows:

Copy Code code 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 work just as they are described, and you want to make sure that the first letter of a string is uppercase, and the rest is lowercase, you need to use a conforming method. As shown below:
Copy Code code 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
?>

Third, and HTML tag-related string formatting

HTML input forms and URLs are additional resources for users to submit data to the server, if not handled well, it is possible to become hackers attack the server portal. For example, when a user publishes an article, if it contains code such as HTML formatting tags or JavaScript page-shift, the direct output display will definitely use the layout of the page to change. Because the code is sent to the browser, the browser will interpret it in a valid code. Therefore, in the PHP script, the user submits the data content must first deal with. In PHP, we provide a very comprehensive HTML-related string formatting function, which can effectively control the output of HTML text.

① function nl2br ()

The string "<br>" that is exported in the browser wraps, and many people are accustomed to using "\ n" as a newline symbol, but the string's newline character is not recognized in the browser. Even if you have multiple lines of text, this is the only line that is displayed in the browser. The NL2BR () function inserts the HTML newline character "<br/>" before each new line "\ n" in the string. The use of this function is shown below:

Copy Code code as follows:

<?php
Echo nl2br ("One line.\nanother line."); Precede "\ n" with the "<br/>" mark
/* Output The following two lines of results
One line.<br/>
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 markup to HTML entities. For example, convert "<" to "<" and convert ">" to ">". 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 converts some of the predefined strings into HTML entities. This function is used in the prevention of user-supplied text that includes HTML tags, such as bulletin boards or guest message board applications. The following are the characters that the function can convert:

★ "&" (and number) is converted to "&".
★ "" "(double quotes) to" ".
★ "'" (single quotation mark) to "'".
★ "<" (less than) converted to "<".
★ ">" (greater than) converted to ">".

The prototype of the function is as follows:

Copy Code code as follows:

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

The first parameter in the 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 converts only double quotes while preserving single quotes; ent_quotes converts both quotes; Ent_noquotes does not convert quotes. The third parameter specifies the character set of the string being processed, and the default character set is "Iso88511-1".

Copy Code code as follows:

<body>
<?php
$str = "<B>WebServer:</B> & ' Linux ' & ' Apache '"; String 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 quotes
echo "<br>\n";
Echo Htmlspecialchars ($str, ent_noquotes); Convert HTML tags and do not convert quotation marks
echo "<br>\n";
?>
</body>

Output results in the browser

Copy Code code as follows:

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

If you view the source code in a browser, you see the following results:
Copy Code code as follows:

<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 use syntax of the Htmlspecialchars () function, which can escape more HTML characters. The following code is an example of the use of the Htmlentities () function:

Copy Code code as follows:

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

When working with data submitted in a form, you need to process the quotation marks not only by converting HTML markup symbols and some special characters into HTML entities through the functions described earlier. Because the "'", "" "" "and" \ "characters in the submitted form data will be automatically preceded by a slash" \ ". This is because the option MAGIC_QUOTES_GPC in the PHP profile php.ini is on, the default is open, and if you do not close it, use the function stripslashes () to remove the backslash. If you do not process the data in the database, you may be mistaken for a control symbol by the database. The function stripslashes () has only one processed string as a parameter and returns the processed string. You typically use the Htmlspecialchars () function in conjunction with the Stripslashes () function to work together on the data submitted in the form.

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

function Htmlspecialchars () is necessary to convert markup symbols in function HTML to corresponding HTML entities, and sometimes to directly delete HTML tags entered by users. The Strip_tags () function provided in PHP allows you to delete all HTML tags in a string by default, or you can selectively delete some HTML tags. such as bulletin boards or guest message board, it is quite necessary to use this aspect. For example, when users publish articles in a forum, they can reserve HTML tags that can change the font size, color, bold, and italic, and delete some HTML tags that affect the layout of the page. The prototype of the function strip_tags () looks like this:

Copy Code code as follows:

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

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

<?php
$str = "<font color= ' red ' size=7>linux</font> <i>Apache</i> <u>Mysql</u> <b >PHP</b> ";
echo Strip_tags ($STR); Delete 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 a lot of format-handling functions for strings, as long as you want to format the string you want, you can call the system functions provided in PHP, and you rarely have to define string formatting functions yourself.

① function Strrev ()

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

Copy Code code as follows:

<?php
Echo Strrev ("http://www.lampbrother.net"); Reverse output: ten.rehtorbpmal.www//:p TTH
?>

② function Number_format ()

The Number_format () function formats a number by a thousands group. The function looks like this:

Copy Code code as follows:

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

Copy Code code as follows:

<?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 digits after decimal point
Echo Number_format ($number, 2, ",", "."); Output 123.456.789,00 thousand uses (.) Separated, and retains two decimal places
?>

③ function MD5 ()

With the popularization of Internet, hacker attack has become the heart of network manager. Statistics show that 70% of attacks come from within, so precautions must be taken to contain attacks within the system. The importance of preventing internal attacks is also due to the insider's knowledge of where the data is stored and the importance of information, which makes internal attacks more likely to work. An attacker steals the identity of a legitimate user and communicates with others in a phishing capacity. Therefore, the user should be registered when the password should be encrypted and then added to the database, so as to prevent internal attackers directly query the database authorization table, the identity of legitimate users to steal information.

The MD5 () function is to encrypt a string MD5 algorithm, and return a 32-bit hexadecimal string by default.

Copy Code code as follows:

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

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

A function md5_file () is provided in PHP for MD5 encryption of a file, in a manner 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.