Common string usage

Source: Internet
Author: User
Tags rtrim

Source: http://bbs.phpma.com/read-htm-tid-795.html

 

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 considered/T as an 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. 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
The most common output in PHP is echo, print. both are not real functions, but language structures. Therefore, you do not need to use double brackets (such as ECHO ("test"); print ("test") for calls ")). you can assign values to both outputs:
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 Kiki, iwind said .";
Echo htmlspecialchars ($ Str );
Will output
I love <font> Kiki </font>, 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 a string
+ Line break. 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.

You can try it one by one

 

PS: the more basic it is, the more important it is to remember

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.