Introduction to PHP String Operations tutorial

Source: Internet
Author: User
Tags comparison empty explode net new features strcmp strlen trim
Tutorials | Getting Started | strings

In either language, string manipulation is an important foundation, often simple and important. Just as people speak, there is a body (graphical interface), there is a language (print string?). Clearly, the string can explain more things. PHP provides a large number of string manipulation functions, powerful and easy to use, please see http://cn2.php.net/manual/zh/ref.strings.php in detail. The following will briefly describe its functionality and characteristics.
Weak type
PHP is a weakly typed language, so other types of data can generally be applied directly to string manipulation functions and automatically converted to string types for processing, such as:


PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo substr ("1234567", 1, 3);

And

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo substr (123456,1, 3);

is the same

Defined
A string is typically identified with double or single quotes. Like what

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$str = "I love u";
$str = ' I love u ';


There are some differences between the two. The latter treats all single quotes as characters; Like what

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$test = "Iwind";
$str = "I love $test";
$str 1 = ' I love $test ';
Echo $str; Will get I love Iwind
echo $str 1; Will get I love $test


The same behavior of the following two examples is not the same:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo "I love \test"; Will get I love est, which already treats \ t as escaping
Echo ' I love \test '; Will get I love \test


It is possible to simply assume that the contents of double quotes are "explained" and that single quotes are "WYSIWYG". Obviously, the double quotes form is more flexible, of course, single quotes will apply to some special occasions, this is not explained here.

Output
The most common use of output in PHP is echo,print. Both are not real functions, but language constructs, so it is not necessary to invoke a double parenthesis (such as echo ("test");p rint ("Test"). Both can be assigned at the time of output:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo $str = "Test"; On the one hand output test, on the one hand "test" to the string variable $str
Print $str = "Test";


There are other differences between the two except the names. Print has a return value that always returns 1, and Echo does not, so echo is faster than print:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$return = print "Test";
Echo $return; Output 1


For this reason, print can be applied to compound statements, and Echo cannot:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Isset ($STR) or print "str variable undefined"; Will output "str variable undefined"
Isset ($STR) or echo "str variable undefined";//will prompt parsing error


The echo can output more than one string at a time, and print cannot:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo "I", "Love", "Iwind"; Will output "I love Iwind"
Print "I", "Love", "Iwind"; will prompt for error


Echo,print can also output strings that are called "document syntax," syntax such as:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo <<< Label name
...
String contents
...
Label name;


Like what

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo <<< Test
I love Iwind
Test


Note that the start and end of the statement two label names are the same, and the next label name can not be blank, that is, to below write. The contents of the document syntax output recognize variable names and commonly used symbols, roughly shaped like double quotes.

Out of Echo,print, PHP also provides some functions for formatting strings, such as printf,sprintf,vprintf,vsprintf, which are not detailed here.

Connection
More than two strings are concatenated with "." operator to form a new string in the order of the strings.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$str = "I". Love "." Iwind ";
The $str here is "I love Iwind"; string. Of course, you can also use the. = Operator:
$str = ""; Class
$str. = "I love Iwind";


Initialization is used here because undefined variables produce a notice error when used, or null can simply represent an empty string.

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

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$STR = "Test";
echo strlen ($STR); Will output 4

It's strange that strlen the Chinese and Japanese characters as well as the full-width characters as two or four lengths. Fortunately, mbstring or icon two functions can help solve this problem, such as:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$len = Iconv_strlen ($str, "GBK");
$len = Mb_strlen ($str, "GBK");

Note: The Mbstring module provides a large number of processing functions for strings containing multibyte characters and is recommended for more applications, as this article is about getting started with strings, so it is not intended to be explained in detail.

Separating and connecting
PHP allows you to separate a string into an array by a delimiter, or to synthesize an array into a string. Look at the following example:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$str = "I love Iwind";
$array = Explode ("", $str);

The explode function, which separates the $STR string by a space character, returns an array $array: Array ("I", "Love", "Iwind"). Similar functions to the EXPLODE function are: Preg_split (), Spliti (), Split () and other functions.

In contrast, implode and joins combine an array into a string of functions that have exactly the same function.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$array = Array ("I", "Love", "Iwind");
$str = Implode ("", $array);
The implode function in the example connects each element of the array $array with a space character, returning a string $str: "I love Iwind".


Cutting
A string of the first and the end, may not be the part you want, you can use Trim,rtrim,ltrim functions, respectively, remove a string of two spaces, a string trailing spaces, a string header space.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo Trim ("I love Iwind"); Will get "I love Iwind"
echo RTrim ("I love Iwind"); Will get "I love Iwind"
Echo LTrim ("I love Iwind"); Will get "I love Iwind"

In fact, these three parameters can not only remove the string and the end of the space, you can also remove their second parameter specified characters, such as:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo Trim (", 1,2,3,4,", ","); Will get the 1,2,3,4 at both ends of the "," number was cut off.


Sometimes you see someone using the chop function, which is actually synonymous with RTrim.

Case
For English letters, you can use Strtoupper,strtolower to turn them into uppercase or lowercase.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo Strtoupper ("I love Iwind"); Will get I love Iwind
Echo strtolower ("I love Iwind"); Will get I love Iwind


Comparison
Generally can use!=, = = Compare two objects are equal, so that is two objects, because they are not necessarily all strings, can also be integral type and so on. Like what

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$a = "Joe";
$b = "Jerry";
if ($a!= $b)
{
echo "Not Equal";
}
Else
{
echo "equal";
}

If you compare it with!==,=== (you can see an equal sign), the type of two objects must be strictly equal to return true, otherwise the string will be automatically converted to the appropriate type for comparison by ==,!=.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

22 = = "22"; Returns True
22 = = "22"; return False
Because of this, our program often has unexpected "surprises":
0 = "I love You"; Returns True
1 = "1 I love You";/return True


PHP also has such a set of functions for string comparisons: strcmp,strcasecmp,strncasecmp (), strncmp (), all of which, if the former is larger, return integers greater than 0; If the former is smaller then the integer less than 0 is returned ; If the two are equal, return 0. The principle of comparison is the same as that of other languages.
STRCMP is a string comparison for case sensitivity (i.e., case sensitive):

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo strcmp ("ABCDD", "ABCDE"); Returns 1 (>0), comparing "B" and "B".


STRCASECMP for case-insensitive string comparisons:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo strcasecmp ("ABCDD", "ABCDE"); Returns-1 (<0), comparing "D" and "E"


STRNCMP is used to compare a portion of a string, starting at the beginning of the string, and the third parameter, the length to compare:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo strncmp ("ABCDD", "ABCDE", 3); Returns 1 (>0), comparing ABC and ABC


STRNCASECMP is used as part of a case-insensitive comparison string, starting at the beginning of the string, the third parameter, the length to compare:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo strncasecmp ("ABCDD", "ABCDE", 3); Returned 0, comparing ABC and ABC,
Because it is not case-sensitive, the two are the same.

Another situation is to compare the string size alone, can not achieve our predetermined requirements, such as as usual, 10.gif will be larger than 5.gif, but if the above functions are applied, it will return 1, that is, 10.gif than 5.gif, in this case, PHP provides two natural-contrast functions strnatcmp,strnatcasecmp:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

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


Replace
The meaning of substitution is to change the part of a string so that it becomes a new string outside of the other to meet the new requirements. PHP is usually replaced with str_replace ("What to replace", "string to replace the original content", "original string").

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo str_replace ("Iwind", "Kiki", "I love Iwind, Iwind said"); Will output "I love Kiki, Kiki said"

Replace All "Iwind" in the original string with "Kiki".

Str_replace is case sensitive, so you can't imagine using Str_replace ("Iwind", "Kiki",...) Replaces the "Iwind" in the original string.

Str_replace can also implement a one-to-many, many-to-many substitution, but cannot achieve a One-to-many replacement:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo str_replace (Array ("Iwind", "Kiki"), "people", "I love Kiki, Iwind said");

will be output
I love people, people said
The array ("Iwind", "Kiki") in the first argument is replaced with "people"


PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo str_replace (Array ("Iwind", "Kiki"), Array ("Gentle Man", "Ladies"), "I love Kiki, Iwind said");

Output I love ladies, Gentle Mans said. That is, the elements in the first array are replaced by the corresponding elements in the second array, and if an array is less than the number of elements in the other array, the insufficient is treated as null.

Some similar to this are STRTR, please refer to the manual, their comparison see http://diary.4kiki.net/index.php?action=info&id=372.

In addition, PHP provides Substr_replace, which implements the replacement of a part of the string. The syntax is as follows:
Substr_replace (original string, string to be substituted, position to begin substitution [, replacement length])
Where the start of the substitution is calculated starting at 0 and should be less than the length of the original string. The length to be replaced is optional.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

Echo substr_replace ("Abcdefgh", "DEF", 3); Will output "AbcDEF"
Echo substr_replace ("Abcdefgh", "DEF", 3, 2); Will output "ABCDEFFGH"

In the first example, the substitution begins at the third position ("D"), replacing "defgh" with "DEF".
In the second example, the substitution begins at the third position (i.e. "D"), but replaces only 2 lengths, i.e. to E, so that "de" is replaced with "DEF".

PHP also provides functions such as preg_replace,preg_replace_callback,ereg_replace,eregi_replace to use regular expressions to complete string substitution, please refer to the manual.

Find and Match
There are a lot of functions in PHP for finding or matching or locating, and they all have different meanings. Here we only talk about more strstr,stristr. The latter is the same as the function of the former, the return value is the same, just case-insensitive.
Strstr ("Parent string", "substring") is used to find the first occurrence of a substring in a parent string, and to return the part of the parent string that starts from the substring to the end of the parent string. Like what
Echo strstr ("ABCDEFG", "E"); Will output "EFG"
If the substring cannot be found, an empty return is returned. Because it can be used to determine if a string contains another string:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$needle = "Iwind";
$str = "I love Iwind";
if (Strstr ($str, $needle))
{
echo "Inside has iwind";
}
Else
{
echo "There is no iwind";
}
Will output "There's iwind in there."


HTML related
1,htmlspecialchars ($string)
This is its simplest use to convert some special characters in a string (as the name suggests) and, ', ' <,> to their corresponding HTML entity form:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$str = "I love <font color=\" red\ ">KIKI</FONT>, Iwind said.";
echo Htmlspecialchars ($STR);

will be output
I love <font color= "Red" >kiki</font>, Iwind said.

2,htmlentities ($string)
Converts all characters that can be converted into solid form into solid form.

3,html_entity_decode ($string);
PHP4.3.0 has the opposite function to Htmlentities ($string) after joining.

4,NL2BR ($string)
Converts all newline characters in the string into <br/> + newline characters. Such as:

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

$str = "I love kiki,\n Iwind said";
echo nl2br ($STR);

will be output
I love kiki,<br/>
Iwind said.


Encryption
The most common use of encrypted strings is MD5, which converts a string into a unique string of 32 bits long.

PHP: [Copy to Clipboard]
--------------------------------------------------------------------------------

echo MD5 ("I love Iwind"); Will output "2df89f86e194e66dc54b30c7c464c21c"


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


Here, this introductory tutorial on string operations is over, but the above is just the tip of the iceberg, especially after PHP5 added a lot of new features, so we need to continue to learn it can be very good application.



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.