PHP learning: String operations and Regular Expressions

Source: Internet
Author: User
Tags ereg php and mysql rtrim
ArticleDirectory
    • A). Convert the character to uppercase: strtoupper ()
    • B). Convert the character to lowercase: strtolower ()
    • C). If the first character is a letter, convert it to uppercase: ucfirst ()
    • D). Convert the first letter of each word in the string into uppercase: ucwords ()

Introduction: This is Php Learning: A detailed page for string operations and regular expressions. It introduces PHP, related knowledge, skills, experience, and some PHP source code.

Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 350124 'rolling = 'no'>

Main content:

    1. String formatting;
    2. Concatenate and separate strings using string functions;
    3. String comparison;
    4. Use string functions to match and replace substrings;
    5. Use a regular expression;
String formatting
1. Space removal: trim (), ltrim (), rtrim ()

The TRIM () function removes spaces at the beginning and end.

The ltrim () function removes the starting space.

Remove the trailing space from the rtrim () function.

2. format the string: printf (), sprintf ()

The printf () and sprintf () functions are the same as Echo functions, and both print strings. However, they can implement more complex formats (similar to string. Format () in C ).

The prototype of printf () and sprintf () is as follows:

 
String sprintf (string format [, mixed ARGs ..]); void printf (string format [, mixed ARGs...]);

Sprintf () returns the formatted string. Printf directly outputs the result. These two functions are similar, so printf () is used as an example.

 
$ Boy = "boy"; echo "I Am a $ boy"; echo '<br/>'; printf ("I Am a % s", $ boy );

The output above is the same.

The formats can be of the following types:

All conversion types in format start with %. To print a "%" symbol, you must use two "%"

3. Change the case (a) in the string. Convert the character to uppercase: strtoupper ()
 
$ STR = "I am a boy"; echo strtoupper ($ Str );
B). Convert the character to lowercase: strtolower ()
 
$ STR = "I am a boy"; echo strtolower ($ Str );
C). If the first character is a letter, convert it to uppercase: ucfirst ()
 
$ STR = "I am a boy"; echo ucfirst ($ Str );
D). Convert the first letter of each word in the string into uppercase: ucwords ()
 
$ STR = "I am a boy"; echo ucwords ($ Str );
4. Escape string

The addslashes () function is to convert "to \", or convert "\" to "Double slash.

 
$ STR = '"I Am a [\] Boy."'; echo addslashes ($ Str );

Output: \ "I Am a [\] Boy .\"

The opposite of the addslashes () function is stripslashes ().

Concatenate and separate strings using string functions
1, separator string: explode ()

Its prototype is as follows:

Array explode (string separator, string input [, int limit]);

The returned array is displayed. Use:

$ STR = "1, 2, 3, 4, 5"; $ arr = explode (',', $ Str); foreach ($ arr as $ v) {echo $ v. '<br/> ';}

Returns 1 2 3 4 5

Since there is a separation, there will be integration. Yes, implode () and join () functions are implemented in the opposite way as explode.

$ STR = "1, 2, 3, 4, 5"; $ arr = explode (',', $ Str); echo implode (',', $ ARR );
2. truncation string: substr ()

The prototype of the substr () function is as follows:

String substr (string input, int start [, int length]);

The second parameter indicates the starting position of the truncation.

The third parameter indicates the truncation length.

Use:

$ STR = "I am a boy"; echo substr ($ STR, 2 );

Output: Am a boy

It should be noted that the second and third parameters can be negative. If it is negative, it means starting from the back.

Function reverse_ I ($ Str) {for ($ I = 1; $ I <= strlen ($ Str); $ I ++) {echo substr ($ STR,-$ I, 1);} return;} reverse_ I ('word ');

Return Value: Drow;

String comparison
1. String sorting: strcmp (), strcasecmp (), strnatcmp ()

The prototype of strcmp () is as follows:

Int strcmp (string str1, string str2 );

Returns 0 if the two strings are equal. Returns a positive number if str1 is after str2. This function is case sensitive.

$ Str1 = "2"; $ str2 = "12"; echo strcmp ($ str1, $ str2 );

Returns 1, indicating that it is alphabetically arranged. the first character of $ str1 is greater than the first character of $ str2.

The strcasecmp () function is the same as the strcmp () function except case insensitive.

Strnatcmp () is sorted in the order that people prefer. It is case insensitive.

$ Str1 = "2"; $ str2 = "12"; echo strnatcmp ($ str1, $ str2 );

Returns-1, indicating that 12 is greater than 2.

2. Obtain the string length: strlen ()

Strlen ("Hello"), the output is 5.

Use string functions to match and replace substrings
1. Search for strings: strstr (), strchr (), strrchr (), and strssr ()

These functions look similar, so it's hard to remember !~~

The most common function is the strstr () function. The strchr () function is the same as the strstr () function. Although strchr () is used to find a character.

The following is a prototype of the strstr () function:

 
String strstr (string haystack, string needle );
 
The first parameter is the entire string.

The second parameter is the substring to be searched.

If a match is found, the function returns haystack from front of needle; otherwise, false is returned. If more than one needle exists, the returned string starts from the position where the first needle appears.

A). Exact match

 
$ Str1 = "to all, I am very sad to tell you that I 've just been fired. it has been my pleasure to work with all of you and I wish you only the best going forward. "; echo strstr ($ str1, 'very ');

Output: very sad to tell you that I 've just been fired. It has been my pleasure to work with all of you and I wish you only the best going forward.

B). Multiple matches

 
$ Str1 = "to all, I am very sad to tell you that I 've just been fired. it has been my pleasure to work with all of you and I wish you only the best going forward "; echo strstr ($ str1, 'been ');

Output: been fired. It has been my pleasure to work with all of you and I wish you only the best going forward.

The strstr () function has two variants. The first is the stristr () function, which is almost the same as the strstr () function, but the difference is case insensitive.

The second is the strrchr () function, which is almost the same as strstr (), but returns the string haystack from the front of the last position where the needle is located.

The second parameter of this function is a character.

 
$ Str1 = "to all, I am very sad to tell you that I 've just been fired. it has been my pleasure to work with all of you and I wish you only the best going forward. "; echo strrchr ($ str1, 'w ');

Output: Ward.

2. Locate the string: strpos (), strrpos ()

The strpos () function is similar to the strstr () function. But it does not return a string, but returns the position of the substring in the entire string. This is what we usually use. It is faster than strstr.

The strpos () function prototype is as follows:

 
Int strpos (string haystack, string needle, int offset );

The third parameter is optional, indicating the start position of the search.

 
$ Str1 = "Hello word"; echo strpos ($ str1, 'O ');

Output: 4, starting from 0. You can also use a substring for demonstration purposes.

 
$ Str1 = "Hello word"; echo strpos ($ str1, 'O', 5 );

Output: 7. The search starts from Location 5, and the "O" of location 4 is invisible.

The strrpos () function is almost the same, but returns the position of the substring in the entire string for the last time.

$ Str1 = "Hello word"; echo strrpos ($ str1, 'O ');

Output: 7. It indicates 7 of the last position of "O" in Hello word.

Note that false in PHP is equal to 0. If strpos () or strrpos () is returned, false is returned (not found) or the first character is found (the starting position of the first character is 0 ),

You cannot tell whether to find or not. What should we do? You can only use the "=" constant equation to avoid this problem.

 
$ Str1 = "Hello word"; $ position = strrpos ($ str1, 'H'); // the first character is found, $ position = 0if ($ position = false) {echo 'not found';} else {echo $ position ;}
3. Replace the substring: str_replace (), substr_replace ()

The following is a prototype of the str_replace () function:

 
Mixed str_replace (mixed needle, mixed new_needle, mixed haystack [, Int & COUNT]);

The third parameter is optional. It contains the number of replacement operations to be performed.

Returns the replaced string.

 
$ Str1 = "Hello word"; echo str_replace ('word', 'China', $ str1 );

Output: Hello China

The substr_replace () function is used to find and replace a specific substring in the string at a given position. The prototype is as follows:

String substr_replace (string, string replacement, int start [, int length]);

This function uses the string replacement to replace a part of the entire string. The specific part depends on the start position and the value of the optional parameter length.

Note that if the start value is 0 or a positive value, the offset is calculated from the string. If it is a negative value, it is an offset from the end of the string.

Use Regular Expressions
1. Search for substrings: ereg (), eregi ()

The prototype of the ereg () function is as follows:

 
Int ereg (string pattern, string SEARCH, array [matches]);

Find the Regular Expression Pattern in the search string. If a string matches the pattern expression, the strings will be stored in the array matches, each array element corresponds to a subexpression.

Except case-insensitive, The eregi () function has the same functionality as ereg.

 
$ Str1 = "xxx@gmail.com.cn"; if (! Eregi ('[A-Z0-9. _ % +-] + @ [A-Z0-9. -] + \. [A-Z] {2, 4} ', $ str1) {echo' is not the correct email ';} else {echo 'right ';}
2. Replace the substring: ereg_replace (), eregi_replace ()

Similar to the str_replace () function, only the two use regular expressions as parameters.

The ereg_replace () prototype is as follows:

String ereg_replace (string pattern, string replacement, string SEARCH );
 
$ Str1 = "123123@gmail.com.cn"; echo ereg_replace ('[A-Z0-9. _ % +-] + @', '** @', $ str1 );

Output: ** @ gmail.com.cn

The eregi_replace function is the same as ereg_replace () except case-insensitive.

3. Separator string: Split ()

The prototype of the function split () is as follows:

 
Array split (string pattern, string SEARCH [, int Max]);

The third parameter is optional, indicating the number of elements in the array.

The returned value is an array.

 
$ Str1 = "123123@gmail.com.cn"; $ arr = Split ('\. | @ ', $ str1); While (List ($ key, $ value) = each ($ ARR) {echo' <br/> '. $ key. '--'. $ value ;}

Output:

0--123123

1 -- Gmail

2 -- com

3 -- CN

The split () function is similar to the explode () function. The former uses a regular expression as the separator, and the latter uses a string as the separator.

Reference: PHP and MySQL. Web Development

Love J2EE follow Java Michael Jackson video station JSON online tools

Http://biancheng.dnbcw.info/php/350124.html pageno: 3

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.