PHP string and string manipulation Tutorial _php Tutorial

Source: Internet
Author: User
PHP string is a type of data in PHP, the string in the program development occupies a heavy position, let me give PHP beginners to introduce some of the PHP string based on knowledge and usage instructions.

Output string

In PHP, there are four ways to output strings. The ECHO structure can output multiple values at once; print () can output only one value; printf () can format the output; Print_r () can output an array, which is good for debugging. Here's a description.

1. Echo
echo is a keyword in PHP that has no return value. In the notation, it can omit parentheses. The following code:

The code is as follows Copy Code

Echo ' Test String ';
Echo (' Test String ');

2. Print
Print is also a keyword in PHP, it has a return value, generally returns true, the case should not return false. As with Echo, it is possible to omit the parentheses in the notation. The following code:

The code is as follows Copy Code

print ' Test String ';
Print (' Test String ');

3. printf
printf can format the output of a string like the C-language printf. It has the same format as the C language and is preceded by%. Its descriptor is defined as follows.

The



B parameter is an integer, showing the binary
C parameter as an integer, displaying the corresponding ASCII character
D parameter as an integer, displaying its decimal
F parameter as double precision, displaying the floating point number
E parameter as double precision, and displaying the scientific count
G The parameter is double, displayed as a floating-point number, or a scientific count type
o parameter is an integer that displays its octal
s parameter as a string, displayed as a string
u parameter is an unsigned integer, and its decimal
x/x parameter is an integer that displays its hexadecimal (case-by-casing)
% Output%
To illustrate:
F,e default six digits after the decimal point, g in more than six bits (plus decimal), will be rounded, if the value after rounding is less than 1000000 will be directly output, greater than 1000000 will be displayed as scientific counting type. f The result of a value greater than 1.2e23 output is incorrect.
the above except%, the other can specify the total number of outputs (decimal point, E is one), and you can specify 0 or a space is a complement, you can also specify whether the complement is left or right. The
F,e can specify the number of digits after the decimal point.
such as%5d indicates that the total output number is 5, insufficient left fill space,%05d indicates the total output number is 5, insufficient left 0,%05.1f indicates the total output number is 5, insufficient left to fill 0, 1 digits after the decimal point,%-05.1f indicates the total output number is 5, insufficient right to fill 0, 1 digits after the decimal point;
Example code:

The code is as follows Copy Code
printf ("%7.2f", 1.2); "1.20"
printf ("%-07.2f", 1.2); "1.20000"

4. sprintf
sprintf and format conversion are like printf, the difference is that printf is output directly, and sprintf returns a formatted string.

5. Print_r and Var_dump
Both the Print_r and var_dump can output arrays and objects, but the output of the Print_r to the boolean is not obvious; the var_dump output is verbose and much more commonly used for debugging.
The following code:

The code is as follows Copy Code
$v = new test ();
Print_r ($v);
Var_dump ($v);
Class Test {
public $num = 1;
Public $str = "222";
Public $bln = true;
function Test () {
Global $num;
}
}

The result is:

The code is as follows Copy Code
Test Object
(
[num] = 1
[str] = 222
[BOOL] = 1
)
Object (Test) #1 (3) {
["Num"]=>
Int (1)
["Str"]=>
String (3) "222"
["BOOL"]=>
BOOL (TRUE)
}


String comparisons and lookups

1. String comparisons

In PHP, you can compare strings with = = (double equals) or = = = (three equals). The difference between the two is that the double equals is not a comparison type, the three equals is the comparison type, it does not convert the type, and if there is a number type value on both sides of the equal sign, the second value is converted to a number and then compared. In this case, if it is a pure string or null, it is converted to 0 for comparison. Similarly, the size of the number is the same as the equal sign, which may result in incorrect results when compared.
Therefore, the comparison string can be used with PHP's own function strcmp and strcasecmp. Where strcasecmp is a variant of strcmp, it converts the string to lowercase before comparing it. The following code:

The code is as follows Copy Code

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

The result is (the 1th to 3rd result is wrong, only the 4th one is right):

BOOL (TRUE)
BOOL (TRUE)
BOOL (TRUE)
Int (-1)
2. String processing
1. Sub-string


The code is as follows Copy Code
$sub = substr (String, start[, length]);

2. Substring substitution

$newstring = Substr_replace (String, new, start[, length]);
Use this function to implement the insertion and deletion of strings. The start and length of this function can be negative. Each one is calculated from the back and retains the last few replacements.
3. String reverse Order

The code is as follows Copy Code

$newstring = Strrev (string);

4. Repeating strings

The code is as follows Copy Code

$newstring = Str_repeat (string, count);

Returns a new string that repeats the count of times string.
5. Populating strings

$newstring = Str_pad (To_pad, length[, with[, type]]);

Where type is: Str_pad_right (default), Str_pad_left, and Str_pad_both three; with default is a space. The function indicates that the To_pad string is populated with a string of length. The following code:

The code is as follows Copy Code

Sub-string
Var_dump (substr (' 1234567890 ', 8)); 90
Var_dump (substr (' 1234567890 ', 0, 2)); 12
Inverse direction substring
Var_dump (substr (' 1234567890 ',-8)); 34567890
Var_dump (substr (' 1234567890 ',-8,-2)); 345678
Var_dump (substr (' 1234567890 ',-8, 2)); 34

Insert
Var_dump (Substr_replace (' 1234567890 ', ' A ', 0, 0)); a1234567890
Delete
Var_dump (Substr_replace (' 1234567890 ', ', 8)); 12345678
Reverse direction Delete
Var_dump (Substr_replace (' 1234567890 ', "',-2,-1)); 123456780
Replace
Var_dump (Substr_replace (' 1234567890 ', ' A ', 0, 1)); a234567890
Reverse direction substitution
Var_dump (Substr_replace (' 1234567890 ', ' a ',-2,-1)); 12345678a0

String inversion
Var_dump (Strrev (' 1234567890 ')); 0987654321

Repeating string
Var_dump (Str_repeat (' 12 ', 3)); 121212

padding string
Var_dump (Str_pad (' A ', 10, ' 12 ')); a121212121
Var_dump (Str_pad (' A ', ten, ' n ', str_pad_left)); 121212121a
Var_dump (Str_pad (' A ', ten, ' n ', Str_pad_both)); 1212a12121

3. Breaking strings
In PHP, the decomposition of the string with explode, combined with implode (join is the alias of implode), tagged with strtok. There is another function slipt can also be decomposed (regular decomposition), but after 5.3 version is not recommended. In addition, PHP also has a sscanf () function, which is used to read the string.
When Strtok is marked, it is initialized with Strtok ($STR, $token) and continues to be evaluated with Strtok ($token).
The code is as follows:

copy code

$str = ' All-in-all ';
$arr 1 = Explode (', ', $str); Array (' 1 ', ' 2 ', ' 3 ')
$arr 2 = explode (', ', $str, 2);//Array (' 1 ', ' 2,3 ')

$str 1 = implode (', ', $arr 1);//' 1, 2, 3 '

$str 2 = strtok ($str, ', ');//1
$str 3 = strtok (', ');//2
$str 4 = strtok (', ');//3

//Array (86, 10, 88888888, ' Beijin ')
$arr 3 = sscanf (' +86 (Ten) 88888888 Beijin ', ' +%d (%d)%d%s ');

4. String Lookup
In PHP, the search for strings has three series. Returns the position, return string, and mask number matching. Where the function of the return position has two, strpos () and Strrpos (); The return string also has two strstr () and STRCHR (); The function that returns the number of mask matches is strspn () and strcspn ().
The strpos represents the first occurrence of the string to be searched, counting from the left, and the strrpos representing the first occurrence of the string to be searched.
Strstr represents the count from the left, returns the substring to find the first to the end of the string (including the lookup string), which can be represented by ASCII numbers when looking for a character, stristr for a size-insensitive lookup; STRCHR is an alias for Strstr. STRRCHR returns the substring at the end of the string.
The STRSPN represents the number of characters from the left count, the substring preceding the first non-mask, and the number of characters of the substring before the first occurrence of the mask before the STRCSPN represents the count from the left.
Example code:

The code is as follows Copy Code

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

$str 1 = "12345 12345 12345";
$len = strspn ($str 1, ' 12345 '); 5
$len = strcspn ($str 1, "); 5


Common string manipulation

1. Accessing a single character
In PHP, you can use a string as an array of characters, and you can access the string directly using the array's access method. such as $str[0].
It is important to note that access can be problematic if the characters are outside the ASCII code. Because this type of access can only get one byte.

2. Remove whitespace characters
In PHP, you can use trim (), LTrim (), RTrim () Three functions to remove white space characters at the beginning or end of a string.
where trim () is used to remove whitespace characters before and after characters; LTrim () is used to delete white space characters to the left of characters; RTrim () is used to remove whitespace characters to the right of a character.
By default, the following characters are removed: spaces (| Ox20), Tab tab (n| Ox09), line break (n| OXOA), carriage return (r|0x0d), null character (| Ox00).
can also be specified in the parameters themselves.

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

4. HTML Escape
HTML escaping is a string that converts a string into an HTML display. In this, PHP has two functions to implement this function.
Htmlentities () converts all the characters that can be converted into HTML in the form of an extra space.
Htmlspecialchars () converts the necessary (ampersand &, double-quotes, single-quote, greater-than, less-than-sign) into HTML form.

5. URL Escape
URL escaping refers to converting a string into a URL string. In this, PHP has two functions to implement this function.
UrlEncode () and UrlDecode () are converting spaces into + numbers, others to URL strings, the former to convert, and the latter to reverse
Rawurlencode () and Rawurldecode () are converting spaces to% 20th, which is the normal URL string, the other to the URL string, the former conversion, the latter conversion

6. SQL escape
PHP is the most relevant two databases (MySQL and PostgreSQL) are the backslash for the escape character (Oracle is its own definition, other databases are not tested), this PHP with the addslashes () function to add these backslashes, with stripcslashes () function to remove these backslashes

http://www.bkjia.com/PHPjc/628630.html www.bkjia.com true http://www.bkjia.com/PHPjc/628630.html techarticle PHP string is a type of data in PHP, the string in the program development occupies a heavy position, let me give PHP beginners to introduce some of the PHP string based on knowledge and usage instructions. ...

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