PHP string operation tutorial

Source: Internet
Author: User

Regardless of the language, string operations are an important foundation, often simple and important. Just as people speak, they generally have shapes (graphical interfaces) and languages (print strings ?), Obviously, strings can explain more things. PHP provides a large number of string operation functions, powerful, easy to use, please refer to the http://cn2.php.net/manual/zh/ref.strings.php. The following will briefly describe its functions and features.

Weak type

PHP is a weak type language, so other types of data can be directly applied to string operation functions, and automatically converted to the string type for processing, such:

Echo substr ("1234567", 1, 3 );
And
Echo substr (123456,1, 3 );
Is the same

Definition

A string is usually identified by double quotation marks or single quotation marks. For example

$ Str = "I love u ";
$ Str = 'I love U ';

The two have some differences. The latter treats all single quotes as characters; the former is not. For example

$ Test = "iwind ";
$ Str = "I love $ test ";
$ Str1 = 'I love $ test ';
Echo $ str; // I love iwind
Echo $ str1; // I love $ test

The two examples of the same behavior are different:

Echo "I love test"; // you will get the I love est, which has been treated as escape
Echo 'I love test'; // you will get the I love test

Therefore, we can simply think that the content in double quotation marks is "interpreted", and the single quotation marks are "What you see is what you get" (in particular, ''will be considered as ''). Obviously, double quotation marks are more flexible. Of course, single quotation marks are applicable to some special occasions and will not be described here.

Output

Echo is the most common output in PHP, and print is not a real function, but a language structure. Therefore, you do not need to use double brackets (for example

Echo ("test"); print ("test"). Both values can be assigned during output:
Echo $ str = "test"; // outputs test, and assigns test to the string variable $ str.
Print $ str = "test ";

The two have different names. Print has a returned value and returns 1 for a while echo does not. Therefore, echo is faster than print:

$ Return = print "test ";
Echo $ return; // output 1

For this reason, print can be applied to compound statements, but echo cannot:

Isset ($ str) or print "str variable undefined"; // output "str variable undefined"
Isset ($ str) or echo "str variable undefined"; // an analysis error is prompted.

Echo can output multiple strings at a time, but print cannot:
Echo "I", "love", "iwind"; // output "I love iwind"
Print "I", "love", "iwind"; // an error is returned.

Echo and print can also output a string called "Document Syntax". The syntax is as follows:
Echo <Tag Name
...
String content
...
Tag name;
For example

Echo <test
I love iwind
Test;

Note that the two label names of the statement start and end are the same, and there cannot be blank before the last label name, that is, the top label should be written. The content of the syntactic output of the document recognizes variable names and common symbols, which are roughly the same as double quotation marks.

In addition to echo and print output, PHP also provides some functions for formatting strings, such as printf, sprintf, vprintf, and vsprintf.
Connection

Two or more strings are connected using the "." operator to form a new string in the order of strings.

$ Str = "I". "love". "iwind ";
Here $ str is "I love iwind"; string. Of course, you can also use the. = Operator:
$ Str = ""; // Initialization
$ Str. = "I love iwind ";

Initialization is used here because the undefined variable will generate a notice error during use. "" Or null can simply represent an empty string.

Length

PHP provides the strlen function to calculate the length of a string:

$ Str = "test ";
Echo strlen ($ str); // output 4

It is strange that strlen calculates Chinese characters such as China and Japan and all-round characters as two or four lengths. Fortunately, the two functions mbstring or icon can help solve this problem, for example:

$ Len = iconv_strlen ($ str, "GBK ");
$ Len = mb_strlen ($ str, "GBK ");

Note: The mbstring module provides a large number of processing functions for strings containing multi-byte characters. It is recommended that you add more applications. This article is about getting started with strings, so it is not intended to be explained in detail.

Separation and Connection

PHP allows you to separate a string into an array by a separator, or combine an array into a string. See the following example:

$ Str = "I love iwind ";
$ Array = explode ("", $ str );

The above explode function separates the $ str string by space characters and returns an array $ array: array ("I", "love", "iwind "). functions similar to explode functions include preg_split (), spliti (), and split.

In contrast, implode and join can combine an array into a string, which has the same functions.

$ Array = array ("I", "love", "iwind ");
$ Str = implode ("", $ array );

In this example, the implode function concatenates each element of the array $ array with a space character and returns a string $ str: "I love iwind ".

Crop

If the beginning and end of a string are not what you want, you can use functions such as trim, rtrim, and ltrim to remove spaces at both ends of a string and spaces at the end of a string, A string with leading spaces.

Echo trim ("I love iwind"); // you will get "I love iwind"
Echo rtrim ("I love iwind"); // you will get "I love iwind"
Echo ltrim ("I love iwind"); // you will get "I love iwind"

In fact, these three parameters can not only remove spaces at the beginning and end of the string, but also remove the characters specified by their second parameter, such:

Echo trim (", 1, 2, 3, 4,"); // The ", at both ends of 1, 2, 3, and 4 are dropped.

Sometimes we can see that someone uses the chop function, which is actually a synonym function of rtrim.
Case sensitivity

For English letters, you can use strtoupper and strtolower to convert them into uppercase or lowercase letters.

Echo strtoupper ("I love iwind"); // I LOVE IWIND
Echo strtolower ("I love iwind"); // I love iwind

Comparison

Generally, it can be used! =, = Compares two objects to see if they are equal. Therefore, they are two objects, because they are not all strings or integers. For example

$ A = "joe ";
$ B = "jerry ";
If ($! = $ B)
{
Echo "not equal ";
}
Else
{
Echo "equal ";
}

If yes! =, = (An equal sign is displayed). If the two objects are compared, the return value is true only when they are of the same type. Otherwise, the return value is = ,! = The string is automatically converted to the corresponding type for comparison.

22 = "22"; // return true
22 = "22"; // return false
Because of this, we often encounter unexpected "accidents" in our programs ":
0 = "I Love You"; // return true
1 = "1 I love you"; // return true

PHP also has such a group of functions used for string comparison: strcmp, strcasecmp, strncasecmp (), strncmp (). If the former is greater than the latter, an integer greater than 0 is returned; if the former is smaller than the latter, an integer smaller than 0 is returned. If the two are equal, 0 is returned. their comparison principles are the same as those of other languages.
Strcmp is a case-sensitive string comparison:

Echo strcmp ("abcdd", "aBcde"); // returns 1 (> 0), comparing "B" and "B"

Strcasecmp is used for case-insensitive string comparison:

Echo strcasecmp ("abcdd", "aBcde"); // returns-1 (<0), comparing "d" and "e"

Strncmp is used to compare a part of a string, starting from the beginning of the string, and the third parameter, which is the length to be compared:

Echo strncmp ("abcdd", "aBcde", 3); // returns 1 (> 0), comparing abc and aBc

Strncasecmp is used to compare a part of a case-insensitive string. It starts from the beginning of the string and the third parameter is the length to be compared:

Echo strncasecmp ("abcdd", "aBcde", 3); // returns 0, comparing abc and aBc. The two are the same because they are case insensitive.

Another scenario is to compare the size of a string to meet our predefined requirements. For example, 10.gif is larger than 5.gif as usual, but if the above functions are applied,-1 is returned, in this case, PHP provides two natural comparison functions, strnatcmp and strnatcasecmp:

Echo strnatcmp ("10.gif"," 5.gif"); // return 1 (> 0)
Echo strnatcasecmp ("10.GIF"," 5.gif"); // return 1 (> 0)

Replace

Replacement is to change a part of a string to a new character string to meet new requirements. In PHP, use str_replace ("content to be replaced", "string to replace the original content", and "original string") to replace.

Echo str_replace ("iwind", "kiki", "I love iwind, iwind said"); // output "I love kiki, kiki said"
Replace all "iwind" in the original string with "kiki ".

Str_replace is case sensitive, so you cannot imagine replacing the "IWIND" in the original string with str_replace ("iwind", "kiki ".

Str_replace can also be used to replace multiple-to-one and multiple-to-many, but cannot replace one-to-multiple:

Echo str_replace (array ("iwind", "kiki"), "people", "I love kiki, iwind said ");
Will output
I love people, people said
Array ("iwind", "kiki") in the first parameter is replaced with "people"

Echo str_replace (array ("iwind", "kiki"), array ("gentle man", "ladies"), "I love kiki, iwind said ");
Output I love ladies and gentle man said. That is to say, the elements in the first array are replaced by the corresponding elements in the second array. If there is an array with fewer elements than the other array, the insufficiency will be treated as null.

Similar to strtr, see the manual for usage.

In addition, PHP also provides substr_replace to replace some strings. Syntax:
Substr_replace (original string, string to be replaced, starting position [, length of replacement])
Here, the starting position of replacement starts from 0 and should be smaller than the length of the original string. The length to be replaced is optional.
Echo substr_replace ("abcdefgh", "DEF", 3); // output "abcDEF"
Echo substr_replace ("abcdefgh", "DEF", 3, 2); // output "abcDEFfgh"
In the first example, replace "defgh" with "DEF" starting from the third position (that is, "d"
In the second example, it is also replaced from the third position (that is, "d"), but only two lengths can be replaced, that is, to e, therefore, replace "de" with "DEF ".

PHP also provides functions such as preg_replace, preg_replace_callback, ereg_replace, and eregi_replace to use regular expressions to replace strings. For usage instructions, see the manual.
Search and match

PHP has many functions for searching, matching, or locating. They all have different meanings. Here we will only describe strstr, stristr. The latter and the former functions, the return values are the same, but not case sensitive.
Strstr ("parent string", "sub-string") is used to locate the first occurrence of a sub-string in the parent string, and return the portion of the parent string from the start of the sub-string to the end of the parent string. For example

Echo strstr ("abcdefg", "e"); // output "efg"
If the substring is not found, null is returned. It can be used to determine whether a string contains another string:
$ Needle = "iwind ";
$ Str = "I love iwind ";
If (strstr ($ str, $ needle ))
{
Echo "contains iwind ";
}
Else
{
Echo "there is no iwind ";
}
The output "contains iwind"

HTML-related

1, htmlspecialchars ($ string)

This is its simplest usage. It converts some special characters in a string (as the name suggests) &, ', "<,> into their corresponding HTML Entity form:

$ Str = "I love <font color =" red "> kiki </font>, iwind said .";
Echo htmlspecialchars ($ str );

Will output
I love kiki, iwind said.

2, htmlentities ($ string)

Convert all characters that can be converted to the Entity form.

3, html_entity_decode ($ string );

PHP4.3.0 and later versions have functions opposite to htmlentities ($ string.

4, nl2br ($ string)

Converts all linefeeds in the string into <B r/> + linefeeds. For example:

$ Str = "I love kiki, \ n iwind said .";
Echo nl2br ($ str );

Will output
I love kiki,

Iwind said.

Encryption

The most common encryption string is md5, which converts a string into a 32-bit character string.

Echo md5 ("I love iwind"); // output "2df89f86e194e66dc54b30c7c464c21c"

PHP5 adds a second parameter to md5 so that it can output a 16-bit encrypted string.

At this point, the Getting Started tutorial on string operations is over, but the above is just the tip of the iceberg, especially after PHP5, a large number of new features are added, therefore, we need to constantly learn it before it can be well applied.

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.