PHP string Operations Getting Started Tutorial _php tutorial

Source: Internet
Author: User
Tags rtrim strcmp
In either language, string manipulation is an important foundation, often simple and important. As people speak, there is usually a form (graphical interface), a language (print string?). ), obviously the string can explain more things. PHP provides a number of string manipulation functions, powerful, easy to use, see http://cn2.php.net/manual/zh/ref.strings.php for details. The following will briefly describe its features and features.

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:


echo substr ("1234567", 1, 3);
And
Echo substr (123456,1, 3);
is the same.


Defined

A string is typically identified by double or single quotation marks. Like what


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

There are some differences between the two. The latter treats the contents of all single quotes as characters, while the former is not. Like what


$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 is different for the following two examples:


echo "I love Test"; Will get I love est, which already treats T as escaping
echo ' I love test '; Will get I love test

Thus, it is simple to think that the contents of the double quotes are "interpreted", and the single quotes are "WYSIWYG" (specifically, "will be considered as a"). It is obvious that the double quotation marks are more flexible, and of course the single quotation marks will apply to some special occasions, which are not described here.

Output

The most commonly used output in PHP is echo,print. Neither is a real function, but a language construct, so it is not necessary to use double brackets when calling (for example,


Echo ("Test");p rint ("Test")). Both can be assigned at the time of the output:
echo $str = "Test"; Output test on one hand, assigning "test" to a string variable on the one hand $str
Print $str = "Test";

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


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

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


Isset ($STR) or print "str variable not defined"; Output "str variable not defined"
Isset ($STR) or echo "str variable not defined";//will prompt parsing error



The echo can output multiple strings at a time, while print does not:
echo "I", "Love", "Iwind"; Will output "I love Iwind"
Print "I", "Love", "Iwind"; will prompt for errors


Echo,print can also output a string called "document Syntax", such as:
Echo <<< Tag Name
...
String content
...
Label name;
Like what


echo <<< Test
I love Iwind
Test

Note that the two tag names of the start and end of the statement are the same, and the next label name must not be blank before it is shelf written. The contents of the document syntax output identify variable names and common symbols, roughly the same as double quotation marks.

In addition to the output 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 connected with "." operator, which forms a new string in the order of the strings.


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

The initialization is used here because undefined variables are used to produce a notice error, "" or null to simply represent an empty string.

Length

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


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

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


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

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

Separating and connecting

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


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

The explode function above separates the $STR string by a space character and 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 join can combine an array into a single string, which is a function with exactly the same function.


$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 header and tail, may not be the part you want, you can use Trim,rtrim,ltrim and other functions, respectively, to remove a string at both ends of the space, a string trailing space, a string header space.


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 end and end of the space, but also to remove their second parameter specified characters, such as:


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

Sometimes you see someone using the chop function, which is actually a synonym for the RTrim function.
Uppercase and lowercase

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


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

Comparison

You can generally use! =, = = Compare two objects for equality, only two objects, because they are not necessarily all strings, they can be integers, and so on. Like what


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

If you compare with!==,=== (you can see an equal sign), the two object types are strictly equal to return true, otherwise ==,!= will automatically convert the string to the appropriate type for comparison.


22 = = "22"; Returns True
22 = = = "22"; Returns false
Because of this, our program often happens to some unexpected "accidents":
0 = = "I love You"; Returns True
1 = = "1 I love You";//Returns True

PHP also has a set of functions for string comparisons: strcmp,strcasecmp,strncasecmp (), strncmp (), which are all integers greater than 0 if the former is larger than the latter, or integers less than 0 if the former is smaller than the latter. If the two are equal, 0 is returned. They compare the same principles as other language rules.
STRCMP is a string comparison that is used for case sensitivity (that is, case sensitive):


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

STRCASECMP for case-insensitive string comparisons:


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

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


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

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


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

Another case is to compare the string size alone, not up to our predetermined requirements, such as normal 10.gif will be larger than 5.gif, but if the above functions, will return 1, that is, 10.gif than 5.gif, for this case, PHP provides two natural contrast function strnatcmp,strnatcasecmp:


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

Replace

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


Echo str_replace ("Iwind", "Kiki", "I love Iwind, Iwind said"); Will output "I love Kiki, Kiki said"
All "Iwind" in the original string are replaced with "Kiki".

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

Str_replace can also implement many-to-one, many-to-many replacements, but cannot implement a-to-many substitution:


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 parameter is replaced with "people"

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 one array is less than the number of elements in the other array, then the insufficiency will be treated as empty.

Something similar to this is STRTR, please refer to the manual for usage.

In addition, PHP provides a substr_replace that implements a replacement part of the string. The syntax is as follows:
Substr_replace (the original string, the string to replace, the position to begin replacing [, the length of the substitution])
Where the starting substitution is calculated from 0, which should be less than the length of the original string. The length to replace is optional.
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 is initiated from the third position (i.e. "D") to replace "DEFGH" with "DEF".
In the second example, the substitution is made from the third position (i.e. "D"), but only 2 lengths are replaced, i.e. to E, so the "de" is replaced with "DEF".

PHP also provides functions such as preg_replace,preg_replace_callback,ereg_replace,eregi_replace to apply regular expressions to complete string substitution, please refer to the manual for usage.
Find and Match

There are many functions in PHP that are used to find or match or locate, and they all have different meanings. This is just about using more strstr,stristr. The latter is the same as the function of the former, the return values are the same, but not case-sensitive.
Strstr ("Female string", "substring") is used to find the position where the substring first appears in the parent string, and returns the portion of the parent string from the beginning of the substring to the end of the parent string. Like what


Echo strstr ("ABCDEFG", "E"); Will output "EFG"
If no substring is found, then NULL is returned. Because it can be used to determine whether a string contains another string:
$needle = "Iwind";
$str = "I love Iwind";
if (Strstr ($str, $needle))
{
echo "Inside is Iwind";
}
Else
{
echo "There is no iwind";
}
Will output "There's iwind inside."

HTML-related

1,htmlspecialchars ($string)

This is its simplest use, to convert some of the special characters in the string (as the name implies) &amp, ', ' <,> into their corresponding HTML entity form:


$str = "I love Kiki, Iwind said.";
echo Htmlspecialchars ($STR);

will be output
I love Kiki, Iwind said.

2,htmlentities ($string)

Converts all characters that can be converted to solid form into solid form.

3,html_entity_decode ($string);

PHP4.3.0 later added has the opposite function to the htmlentities ($string).

4,NL2BR ($string)

Converts all line breaks in a string to < b R/> + line feed. Such as:


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

will be output
I love Kiki,

Iwind said.

Encryption

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


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

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

Here, the start of the string operation tutorial is finished, but the above is only 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.

http://www.bkjia.com/PHPjc/317290.html www.bkjia.com true http://www.bkjia.com/PHPjc/317290.html techarticle In either language, string manipulation is an important foundation, often simple and important. As people speak, there is usually a form (graphical interface), a language (print string?). ) ...

  • 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.