PHP Learning: Getting Started with string manipulation

Source: Internet
Author: User
Tags array empty explode functions strcmp strlen variable trim

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

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


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

$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

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

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 the double quotes are "explained" and that single quotes are "WYSIWYG" (in particular, ' \ ' will be considered a ' \ '). Obviously, the double quotes form is more flexible, of course, single quotes will apply to some special occasions, this is not explained here.


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:

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:

$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 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:
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:
Echo <<< Label name
String contents
Label name;

Like what
echo <<< Test
I love Iwind

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.


More than two strings are concatenated with "." operator to form 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 = ""; 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.


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.

Something similar to this is STRTR,

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

  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:

$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 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 line breaks in a string to a + newline character. Such as:

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

will be output

I love Kiki,

Iwind said.

Related Article

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.