Home >Backend Development >PHP Tutorial >PHP string operation introductory tutorial_PHP tutorial
Regardless of the language, string manipulation is an important foundation, often simple and important. Just like human speech, it generally has a form (graphical interface) and language (print string?). Obviously strings can explain more things. PHP provides a large number of string operation functions, which are powerful and relatively simple to use. For details, please refer to http://cn2.php.net/manual/zh/ref.strings.php. The following will briefly describe its functions and characteristic.
Weakly typed
PHP is a weakly typed language, so other types of data can generally be directly applied to string operation functions and automatically converted into string types for processing, such as:
echo substr("1234567", 1, 3);
and
echo substr(123456,1, 3);
are the same
Definition
Generally use double quotes or single quotes to identify a string. For example,
$str = "i love u";
$str = 'i love u';
There are some differences between the two. The latter treats all single quotation marks as characters; the former does not. For example
$test = "iwind";
$str = "i love $test";
$str1 = 'i love $test';
echo $str; //Will get i love iwind
echo $str1; //Will get i love $test
The same behavior of the following two examples is also different:
echo "i love test"; // will get i love est, t has been regarded as escape
echo 'i love test'; // will get i love test
so it can be simply considered a double The content in quotation marks is "interpreted", and the content in single quotation marks is "what you see is what you get" (in particular, '' will be recognized as a ''). Obviously, the double quotation mark form is more flexible. Of course, single quotation marks will be suitable for some special occasions, which will not be explained here.
Output
The most commonly used output in PHP is echo and print. Both are not real functions, but language constructs, so there is no need to use double brackets when calling (such as
echo("test");print("test")). Both can be assigned values when outputting:
echo $str="test"; //On the one hand, test is output, On the one hand, assign "test" to the string variable $str
print $str="test";
In addition to the different names, there are other differences between the two. Print has a return value and always returns 1, but echo does not, so echo is faster than print:
$return = print "test";
echo $return; // Output 1
For this reason, print can be used in compound statements, but echo cannot:
isset($str) or print "str variable is undefined"; // Will output "str variable is not defined"
isset($str) or echo "str variable is not defined";// Will prompt analysis error
echo can output multiple strings at a time. Print is not possible:
echo "i ","love ","iwind"; // will output "i love iwind"
print "i ","love ","iwind"; // will Prompt error
echo, print can also output a string called "document syntax", with syntax such as:
echo <<< Tag name
...
String content
...
Tag name;
For example
echo <<< test
i love iwind
test;
It should be noted that the two label names at the beginning and end of the statement are the same, and there must be no blank space before the latter label name, that is, it must be written in a square format. The content of the document syntax output identifies variable names and common symbols, which is roughly the same as the function of double quotes.
In addition to outputting echo and print, PHP also provides some functions for formatting strings, such as printf, sprintf, vprintf, vsprintf, which will not be explained in detail here.
Connection
Use the "." operator to connect two or more strings to form a new string in the order of the strings.
$str = "i " . "love " . "iwind";
$str here is "i love iwind"; string. Of course, you can also use the .= operator:
$str = ""; // Initialization
$str .= "i love iwind";
Initialization is used here because it is not defined The variable will generate a notice error when used, "" 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); // Will output 4
What is a little strange is that strlen treats Chinese, Japanese and other Chinese characters and full-width characters as two or four lengths. Fortunately, the two functions mbstring or icon 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 containing multi-byte characters. It is recommended to apply more. Since this article is about getting started with strings, I will not go into details. Commentary.
Separation and concatenation
PHP allows you to separate a string into an array according to a delimiter, or combine an array into a string. Look at the following example:
$str = "i love iwind";
$array = explode(" ", $str);
The above explode function is Separate the $str string by space characters, and the result returns an array $array:array("i", "love", "iwind"). Similar functions to the explode function include: preg_split(), spliti(), split() and other functions.
In contrast, implode and join can combine an array into a string. They are functions with exactly the same functionality.
$array = array("i", "love", "iwind");
$str = implode(" ", $array);
Example The implode function concatenates each element of the array $array with a space character and returns a string $str: "i love iwind".
Crop
A string head and tail, It may not be the part you want, so you can use trim, rtrim, ltrim and other functions to remove spaces at both ends of a string, spaces at the end of a string, and spaces at the beginning of a string.
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 "); // You will get "i love iwind "
In fact, these three parameters can not only remove the spaces at the beginning and end of the string, but also remove their second The characters specified by the parameters, such as:
echo trim(",1,2,3,4,", ","); // will get the " at both ends of 1,2,3,4 ," was cut.
Sometimes you will see people using the chop function. In fact, it is a synonymous function for rtrim.
Case
For English letters, you can use strtoupper and strtolower to convert 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
Generally, you can use !=, == to compare whether two objects are equal. The reason why they are two objects is because they are not necessarily all strings, they can also be integers, etc. For example
$a = "joe";
$b = "jerry";
if ($a != $b)
{
echo "not equal ";
}
else
{
echo "Equal";
}
If you use !==,===(you can see an extra equal sign ) for comparison, the types of the two objects must be strictly equal to return true; otherwise, using ==,!= will automatically convert the string into the corresponding type for comparison.
22 = = "22"; // Return true
22 === "22"; // Return false
Because of this, some unexpected "accidents" often occur in our program:
0 = = "I love you"; // Return true
1 == "1 I love you"; // Return true
There is also a set of functions for string comparison in PHP: strcmp , strcasecmp, strncasecmp(), strncmp(), they all return an integer greater than 0 if the former is greater than the latter; if the former is less than the latter, return an integer less than 0; if they are equal, return 0 .The principles of their comparison are the same as the rules of other languages.
strcmp is used for case-sensitive (i.e. 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") ; // Return -1 (<0), comparing "d" and "e"
strncmp is used to compare part of the string, starting from the beginning of the string, the third parameter, For the length to be compared:
echo strncmp("abcdd", "aBcde", 3); // Returns 1 (>0), compared abc and aBc
strncasecmp is used to compare part of a string without case sensitivity, starting from the beginning of the string. The third parameter is the length to be compared:
echo strncasecmp("abcdd", " aBcde", 3); // Returns 0, compared abc and aBc, since they are not case-sensitive, they are the same.
There is another situation where simply comparing the string sizes cannot meet our predetermined requirements. For example, normally 10.gif will be larger than 5.gif, but if you apply the above functions, it will return - 1, which means 10.gif is better than 5.gif. For this situation, PHP provides two natural contrast functions strnatcmp and strnatcasecmp:
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 part of a string to make it a new string to meet new requirements. In PHP, str_replace("content to be replaced", "string to replace the original content", "original string") is usually used for replacement.
echo str_replace("iwind", "kiki", "i love iwind, iwind said"); // Will output "i love kiki, kiki said"
will be in the original string All "iwind" are replaced with "kiki".
str_replace is case-sensitive, so you cannot imagine using str_replace("IWIND", "kiki",...) to replace the original string "iwind" in.
str_replace can also achieve many-to-one and many-to-many replacement, but it cannot achieve one-to-many replacement:
echo str_replace(array(" iwind", "kiki"), "people", "i love kiki, iwind said");
will output
i love people, people said
array("iwind" in the first parameter ", "kiki") were replaced with "people"
echo str_replace(array("iwind", "kiki"), array("gentle man", "ladies"), "i love kiki , iwind said");
Output i love ladies, gentle man said. That is to say, the elements in the first array are replaced by the corresponding elements in the second array. If one array has fewer elements than the other, the remaining elements will be treated as empty.
Somewhat similar to this is strtr, please refer to the manual for usage.
In addition, PHP also provides substr_replace to replace part of the string. The syntax is as follows:
substr_replace (original string, string to be replaced, starting replacement position [, replacement length])
Among them, the starting replacement position is calculated from 0 and 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 replacement starts from the third position (i.e. "d"), thereby replacing "defgh" with "DEF"
In the second example, it also starts from the third position (i.e. "d") starts to replace, but it can only replace 2 lengths, that is, to e, so "de" is replaced with "DEF".
PHP also provides preg_replace, preg_replace_callback, ereg_replace, Functions such as eregi_replace apply regular expressions to complete string replacement. Please refer to the manual for usage.
Search and match
There are many functions in PHP for searching, matching or positioning, and they all have different meanings. Here we only talk about the more commonly used strstr and stristr. The functions and return values of the latter and the former are the same, but they are not case-sensitive.
strstr("parent string", "substring") is used to find the first occurrence of the substring in the parent string, and returns the position from the beginning of the substring to the parent string in the parent string Ending part. For example
echo strstr("abcdefg", "e"); //will output "efg"
If the substring is not found, it will return empty.Because it can be used to determine whether a string contains another string:
$needle = "iwind";
$str = "i love iwind";
if (strstr($str, $needle ))
{
echo "There is iwind inside";
}
else
{
echo "There is no iwind inside";
}
will output "Inside There is iwind"
HTML related
1,htmlspecialchars($string)
This is its simplest usage, convert some special characters in the string (as the name suggests)& ,',"<,>Convert into their corresponding HTML entity forms:
$str = "i love kiki, iwind said.";
echo htmlspecialchars($str);
will output
i love kiki, iwind said.
2,htmlentities($string)
Convert all characters that can be converted into entity form into entity form
3,html_entity_decode($string);
Added after PHP4.3.0 and htmlentities($string). The opposite function.
4,nl2br($string)
Converts all newline characters in the string to < br /> + newline characters. For example:
$str = "i love kiki,n iwind said.";
echo nl2br($str);
will output
i love kiki,
iwind said.
Encryption
The most commonly used method of encrypting strings is md5, which converts a string into a 32-bit unique string
<.>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.
At this point, this introductory tutorial on string operations is over, but the above is just the tip of the iceberg. Especially since PHP5 has added a lot of new features, we need to continue to learn. Only then can it be applied well.