Some functions of the PHP string operation

Source: Internet
Author: User
Tags explode php code php script rtrim strcmp strlen trim

1, the string connector
Half-width symbol "." is a string connector that connects two or more two strings to a string. For example:
$name = "cloud-dwelling Community network:";
$url = WWW.51EBK;
Echo $name. $url. ". com";
The results of the operation are: cloud-Habitat Community Network:

2, remove the string and the end of space and special characters
When you enter data, users will often inadvertently enter extra space, in some cases, the string does not allow spaces and special characters, you need to remove the string in the space and special characters.

2.1 Trim () function
The trim () function removes the space at the beginning and end of the string and returns the string that is currently removed from the space.
Syntax format: string trim (String str [, String charlist]);
Parameter str of the trim () function is the string object to manipulate, parameter charlist is an optional parameter, specifies that a particular character needs to be removed from the pending string, and all optional characters are deleted if the argument is not set. The optional values for the parameter charlist are as follows:
Parameter value/description
NULL, NULL value
T tab, tab
N line Feed
x0b Vertical Tab
R return character
"" Space
Note: In addition to the above default filter characters, you can also provide special characters to be filtered in charlist
For example:
$str = "RR (: @_@ Community network @_@:)";
echo Trim ($STR); Remove spaces on both sides of a string
echo "<br/>"; To perform a line wrap
Echo Trim ($STR, RR (::)); Remove special character RR on the left and right side of the string (::)
Run Result:
(: @_@ Community Network @_@:)
@_@ Cloud Habitat Community Network @_@

2.2 LTrim () function
The LTrim () function removes the space on the left side of the string or the specified string.
The syntax format is as follows:
String LTrim (String str[, String charlist]);
For example:
$str = "(: @_@ Community Network @_@:) ";
Echo LTrim ($STR); Remove the space to the left of the string
echo "<br/>";
Echo LTrim ($str, "(: @_@"); Removes the character on the left side of the string @_@:)
The results of the operation are:
(: @_@ Community Network @_@:)
@_@:) of cloud-dwelling community Network

2.3rtrim () function
The RTrim () function removes the space to the right of the string or the specified string.
The syntax format is as follows:
String RTrim (String str[, String charlist]);
For example:
$str = "(: @_@ Community Network @_@:) ";
echo RTrim ($STR); Remove the space to the right of the string
echo "<br/>";
Echo RTrim ($str, "@_@:)    "); Removes the character @_@ to the right of the string:)
The results of the operation are:
(: @_@ Community Network @_@:)
(: @_@ Cloud Habitat Community Network

There are two ways to string escape and restore: One is to manually escape, restore string data, and the other is to automatically escape and restore string data.
1. Manually escaping and restoring string data
strings can be defined in single quotes ('), double quotes (""), delimiters ({}), 3 methods. When using strings, it is most likely that there are characters in the string that are confused with the PHP script, so you must do an escape statement. This needs to precede him with the escape symbol "".
"" is an escape character, and the character immediately following the "" will become meaningless.
For example:
echo "I ' m Tom";
Run the result is: I ' m Tom.
2. Automatically escape and restore string data
Automatic escape, restore string data can be implemented using the Addslashes () function and the stripslashes () function provided by PHP.
The Addslashes () function is used to add a slash to the string.
The Stripslashes () function is used to restore a string that is escaped using the addslashes () function.
For example:
$str = "I ' m Tom";
$str 2 = addslashes ($STR); To escape a special character in a string
Echo $str 2. "<br/>";
Echo stripslashes ($str 2); Restores the escaped string, and then outputs the
Run Result:
I ' m Tom
I ' m Tom
The above two functions implement automatic escape and restore of the specified string. In addition to the methods described above, you can limit the range of strings to be escaped and restored by using the Addcslashes () function and the stripcslashes () function to automatically escape and restore strings within a specified range.
The Addcslashes () function implements the character in the escape string, which is preceded by a backslash in the specified string.
The Stripcslashes () function is used to restore a string that is escaped using the addcslashes () function.
For example:
$str = "self-study php on the Cloud Habitat Community Network";
$str 2 = addcslashes ($str, "self-study PHP on the Cloud Habitat Community Network");
Echo $str 2.    "<br/>"; Output the escaped string
Echo stripcslashes ($str 2); Output the restored string
Run Result:
Self-taught PHP on the cloud Habitat Community Network

PHP provides the strlen function to calculate the length of the string:
$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:
$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:
$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.
$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".
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.
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:
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.
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
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
$a = "Joe";
$b = "Jerry";
if ($a!= $b)
echo "Not Equal";
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 ==,!=.
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):
Echo strcmp ("ABCDD", "ABCDE"); Returns 1 (>0), comparing "B" and "B".
STRCASECMP for case-insensitive string comparisons:
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:
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:
Echo strncasecmp ("ABCDD", "ABCDE", 3); Returns 0, comparing ABC and ABC, because they are not case-sensitive, so they 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:
Echo strnatcmp ("10.gif", "5.gif"); Return 1 (>0)
Echo strnatcasecmp ("10.GIF", "5.gif"); Return 1 (>0)
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").
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:
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"
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, see the Manual for use.
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.
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:
$needle = "Iwind";
$str = "I love Iwind";
if (Strstr ($str, $needle))
echo "Inside has iwind";
echo "There is no iwind";
Will output "There's iwind in there."

String deletion operation

That is true

$result = mysql_query ($sql);
$string = ' {' array ': [';
while ($row = Mysql_fetch_array ($result)) {
$string. = ' {' id ': '. $row [' id ']. ' "}, ';
$string = substr ($string, 0,-1);
$string. = ']} ';
$string = substr ($string, 0,-1) This line of code means that the $string is cropped, starting at No. 0, to the penultimate.

As a result, if there is a result set after the SQL query, but if the result set is empty, the string becomes {"array":]} and the array is corrupted. You want to handle it by determining whether the result set is empty, but using empty ($result) does not work because the result set is empty and needs to be judged by mysql_fetch_array (). So the decision to increase $result for emptiness failed.

The other solution is to start with the string. My idea is that I want to delete the last character, but it must meet a certain condition, such as the last character is ', ', see the PHP API, there is such a method RTrim (), trim () is to delete some special characters, RTrim () is only to the right side of the string operation. It's OK to change the code to the bottom.

$string = RTrim ($string, ', ');
The API for string manipulation provided by PHP is still quite rich.

String conversions to an array

by New One | June 28, 2013 0 Comment
Today I saw in the PHP forum that a friend sent a post to ask PHP how to convert the string to a number of groups; The new first reaction as a PHP programmer is to associate the two functions of explode (), implode (). The new one is also used to convert the array of functions.


Above is the user needs to convert to a PHP array of strings; The following is also a new PHP conversion code

A new PHP code can also solve the problem of string conversions to an array. Finally phper users should be found in the manual above the PARSE_STR () function can convert the string into a PHP array; here's a description of the PARSE_STR () function to make a good impression on your brain.
The Parse_str () function parses the query string into a variable.

Parse_str (String,array)
String: The strings to be converted;
Array: returns to an array;
Overwrite variable with same name if array is not set

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