Php string and string operation tutorial _ PHP Tutorial

Source: Internet
Author: User
Tags strtok
Php string and string operation tutorial details. Php string is a data type in php, and it plays a very important role in program development. let me introduce some php string-based knowledge and instructions for use. Php string is a data type in php, and it plays a very important role in program development. let me introduce some php string-based knowledge and instructions for use.

Output string

In PHP, there are four methods to output strings. The echo structure can output multiple values at a time; print () can only output one value; printf () can format the output; print_r () can output arrays, which is very beneficial for debugging. The following is a one-to-one introduction.

1. echo
Echo is a keyword of PHP, and it does not return a value. In terms of writing, it can omit parentheses. The following code:

The code is as follows:

Echo 'test string ';
Echo ('test string ');

2. print
Print is also a keyword in PHP. it has a returned value. generally, true is returned, and false is returned. In terms of writing, it is the same as echo, and parentheses can be omitted. The following code:

The code is as follows:

Print 'test string ';
Print ('test string ');

3. printf
Printf can format and output a string like printf in C language. The format is similar to that in C, both of which start with %. Its specifiers are defined as follows.



The B parameter is an integer and its binary value is displayed.
The c parameter is an integer that displays the corresponding ASCII characters
The value d is an integer in decimal format.
The f parameter is double-precision and displayed as a floating point number.
The e parameter is double-precision and displayed as a scientific counting type.
The g parameter is double-precision and displayed as a floating point or scientific counter.
The o parameter is an integer and its octal value is displayed.
The s parameter is a string and displayed as a string.
The u parameter is an unsigned integer and is displayed in decimal format.
The x/X parameter is an integer and is displayed in hexadecimal format (case sensitive)
% Output %
Note:
F and e are the six digits after the decimal point by default. if g is more than six digits (plus the decimal point), it is rounded to the nearest integer. if the value is smaller than 1000000, it is output directly, if the value is greater than 1000000, it is displayed as a scientific counting type. F is incorrect when the output value is greater than 1.2e23.
In addition to %, you can specify the total number of digits of the output (decimal point and E are regarded as one digit), and you can specify 0 or space as the complement character, you can also specify whether the complement position is left or right.
F, e can specify the digits after the decimal point.
For example, % 5d indicates that the total number of output digits is 5, and less than left fill space; % 05d indicates that the total number of output digits is 5, and less than left fill 0; % 05.1f indicates that the total number of output digits is 5, and less than left fill 0, 1 digit after the decimal point; %-05.1f indicates that the total number of digits in the output is 5. if not, add 0 to the right and 1 to the decimal point;
Sample code:

The code is as follows:
Printf ("% 7.2f", 1.2); // "1.20"
Printf ("%-07.2f", 1.2); // "1.20000"

4. sprintf
Sprintf and format conversion are the same as printf. The difference between them is that printf outputs directly, while sprintf returns a formatted string.

5. print_r and var_dump
Both print_r and var_dump can output arrays and objects, but print_r is not obvious about boolean output. var_dump outputs are more detailed and are generally used for debugging.
The following code:

The code is as follows:
$ V = new test ();
Print_r ($ v );
Var_dump ($ v );
Class test {
Public $ num = 1;
Public $ str = "222 ";
Public $ bln = true;
Function test (){
Global $ num;
}
}

Result:

The code is as follows:
Test Object
(
[Num] => 1
[Str] = & gt; 222
[Bool] => 1
)
Object (test) #1 (3 ){
["Num"] =>
Int (1)
["Str"] =>
String (3) 222"
["Bool"] =>
Bool (true)
}


String comparison and search

1. string comparison

In PHP, you can use = (double equal sign) or = (third equal sign) to compare strings. The difference between the two is that the two equal signs do not compare the type, and the third equal sign will compare the type, it does not convert the type; when the two equal signs are compared, if there is a number type value on both sides of the equal sign, I will convert another value to a number and then compare it. In this case, if it is a pure string or NULL, it is converted to 0 for comparison. Similarly, the greater than the equal sign is the same. incorrect results may occur during comparison.
Therefore, the strcmp and strcasecmp built-in functions of PHP can be used to compare strings. Strcasecmp is a variant of strcmp, which converts the string to lowercase before comparison. The following code:

The code is as follows:

Var_dump (0 = 'test ');
Var_dump (0 = '');
Var_dump (5> 'T ');
Var_dump (strcmp (5, 'T '));

The result is (1st ~ 3. The result is incorrect. Only 4th are correct ):

Bool (true)
Bool (true)
Bool (true)
Int (-1)
2. String Processing
1. substring


The code is as follows:
$ Sub = substr (string, start [, length]);

2. substring replacement

$ Newstring = substr_replace (string, new, start [, length]);
This function can be used to insert and delete strings. The start and length values of this function can be negative. It indicates that the last few digits are not replaced.
3. reverse string order

The code is as follows:

$ Newstring = strrev (string );

4. duplicate strings

The code is as follows:

$ Newstring = str_repeat (string, count );

Returns a new string that repeats the count string.
5. fill in the string

$ Newstring = str_pad (to_pad, length [, with [, type]);

There are three types: STR_PAD_RIGHT (default), STR_PAD_LEFT, and STR_PAD_BOTH. with is a space by default. The function is used to fill the to_pad string with a string of length. The following code:

The code is as follows:

// Substring
Var_dump (substr ('123', 8); // 90
Var_dump (substr ('123', 0, 2); // 12
// Inverse substring
Var_dump (substr ('20140901',-8); // 1234567890
Var_dump (substr ('20140901',-8,-2); // 1234567890
Var_dump (substr ('20140901',-8, 2); // 34

// Insert
Var_dump (substr_replace ('20170101', 'A', 0, 0); // a1234567890
// Delete
Var_dump (substr_replace ('20140901', '', 8); // 1234567890
// Reverse deletion
Var_dump (substr_replace ('20140901', '',-2,-1); // 1234567890
// Replace
Var_dump (substr_replace ('20170101', 'A', 0, 1); // a234567890
// Reverse replacement
Var_dump (substr_replace ('20140901', 'A',-2,-1); // 12345678a0

// String inversion
Var_dump (strrev ('20140901'); // 1234567890

// Repeat the string
Var_dump (str_repeat ('12', 3); // 121212

// Fill the string
Var_dump (str_pad ('A', 10, '12'); // a1212121
Var_dump (str_pad ('A', 10, '12', STR_PAD_LEFT); // 121212121a
Var_dump (str_pad ('A', 10, '12', STR_PAD_BOTH); // 12a12121

3. break down strings
In PHP, the string is decomposed using explode, combined with implode (join is the alias of implode), and marked with strtok. There is also another function slipt that can be decomposed (regular expression decomposition), but it is not recommended in versions later than 5.3. In addition, PHP also has an sscanf () function for reading strings.
When the strtok tag is used, use strtok ($ str, $ token) for initialization, and use strtok ($ token) to continue the value.
The code is as follows:

The code is as follows:

$ Str = '1, 2, 3 ';
$ Arr1 = explode (',', $ str); // array ('1', '2', '3 ')
$ Arr2 = explode (',', $ str, 2); // array ('1', '2, 3 ')

$ Str1 = implode (',', $ arr1); // '1, 2, 3'

$ Str2 = strtok ($ str, ','); // 1
$ Str3 = strtok (','); // 2
$ Str4 = strtok (','); // 3

// Array (86, 10,888 88888, 'Beijing ')
$ Arr3 = sscanf ('+ 86 (10) 88888888 Beijin', '+ % d (% d) % d % S ');

4. string search
In PHP, there are three series of string searches. Matches the return position, the returned string, and the number of masks. The return position function has two types: strpos () and strrpos (). The return string also has two strstr () and strchr (); the functions that return the number of mask matches include strspns () and strcspns ().
Strpos indicates counting from the left, returns the position where the string to be searched appears for the first time, strrpos indicates counting from the right, and returns the position where the string to be searched appears for the first time.
Strstr indicates the count from the left, and returns the substring (including the string to be searched) from the first time to the end of the string. when the string is searched for, it can be represented by ascii numbers; stristr indicates that the query size is not distinguished; strchr is the alias of strstr; strrchr returns the substring from the last occurrence to the end of the character.
Strspns indicate the count from the left, the number of characters of the substring before the first occurrence of the non-mask; strcspns indicate the count from the left, and the number of characters of the substring before the first occurrence of the mask.
Sample code:

The code is as follows:

$ Pos = strpos ('This a hello world program ', ''); // 4
$ Pos = strpos ('This a hello world program ', 32); // 4

$ Pos = strrpos ('This a hello world program ', ''); // 18
$ Pos = strrpos ('This a hello world program ', 32); // 18

$ Str = strstr ('This a hello world program ', ''); //" a hello world program"
$ Str = strstr ('This a hello world program ', 32); // "a hello world program"

$ Str = stristr ('This a hello world program ', 'A'); // "A hello world program"
$ Str = stristr ('This a hello world program ', 65); // "a hello world program"

$ Str = strrchr ('This a hello world program ', ''); //" program"
$ Str = strrchr ('This a hello world program ', 32); // "program"

$ Str1 = "12345 12345 12345 ";
$ Len = strspns ($ str1, '123'); // 5
$ Len = strcspns ($ str1, ''); // 5


Common string operations

1. access a single character
In PHP, strings can be treated as an array of characters, and strings can be accessed directly using the array access method. For example, $ str [0].
Note that if the character is not an ASCII code, access may fail. Because such access can only get one byte.

2. delete blank characters
In PHP, you can use the trim (), ltrim (), and rtrim () functions to delete the blank characters starting or ending with a string.
Trim () is used to delete the spaces before and after the characters; ltrim () is used to delete the white spaces on the left side of the characters; rtrim () is used to delete the white spaces on the right side of the characters.
By default, the following characters are deleted: Space (| Ox20), TAB (n | Ox09), line feed (n | OxOA), and carriage return (r | 0x0D), empty character (| Ox00 ).
You can also specify it in the parameter.

3. change the case sensitivity.
Strtolower () converts the entire string to lowercase.
Strtoupper () converts the entire string to uppercase.
Ucfirst () converts the first character of the string to uppercase, and other characters remain unchanged.
Ucwords () converts the first character of each word in a string to uppercase, and other characters remain unchanged.

4. HTML escape
HTML escaping refers to converting a string into a string used for HTML display. In this regard, PHP has two functions to implement this function.
Htmlentities () converts all characters except spaces to HTML.
Htmlspecialchars () converts necessary (with symbols &, double quotation marks, single quotes, greater than signs, less than signs) into HTML format.

5. URL escape
URL escape refers to converting a string into a URL string. In this regard, PHP has two functions to implement this function.
Urlencode () and urldecode () convert spaces to the plus sign, and convert other values to URL strings. convert the former to the other, and convert the latter to the other.
Rawurlencode () and rawurldecode () convert the space to % 20, that is, a normal URL string. convert the rest to a URL string. convert the former to the other, and reverse convert the other to the URL string.

6. SQL escape
The two most relevant PHP databases (MySQL and PostgreSQL) are escape characters using backslashes (defined by Oracle and not tested by other databases). In this case, addslashes () is used in PHP () use the stripcslashes () function to delete the backslash.

....

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.