String operations and regular expressions

Source: Internet
Author: User
Tags ereg explode function prototype sprintf strcmp string format strlen trim

String operations and regular expressions

String formatting;
Concatenate and separate strings using string functions;
String comparison;
Use string functions to match and replace substrings;
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:

1 string sprintf (string format [, mixed args...]);

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

1 $ boy = "boy ";

2 echo "I am a $ boy ";

3 echo '<br/> ';

4 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 sensitivity of characters in the string.
A). Convert the character to uppercase: strtoupper ()
1 $ str = "I am a boy ";

2 echo strtoupper ($ str );

B). Convert the character to lowercase: strtolower ()
1 $ str = "I Am A Boy ";

2 echo strtolower ($ str );

C). If the first character is a letter, convert it to uppercase: ucfirst ()
1 $ str = "I am a boy ";

2 echo ucfirst ($ str );

D). Convert the first letter of each word in the string into uppercase: ucwords ()
1 $ str = "I am a boy ";

2 echo ucwords ($ str );

4. Escape string
The addslashes () function is to convert "to", or convert to double slash \, and so on.

1 $ str = '"I am a [] boy ."';

2 echo addslashes ($ str );

Output: "I am a [\] boy ."

The opposite of the addslashes () function is the strips tutorial lashes ().
Concatenate and separate strings using string functions
1, separator string: explode ()
Its prototype is as follows:

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

The returned array is displayed. Use:

1 $ str = "1, 2, 4, 5 ";

2 $ arr = explode (',', $ str );

3 foreach ($ arr as $ v ){

4 echo $ v. '<br/> ';

5}

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.

1 $ str = "1, 2, 4, 5 ";

2 $ arr = explode (',', $ str );

3 echo implode (',', $ arr );

2. Truncation string: substr ()
The prototype of the substr () function is as follows:

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

1 $ str = "I am a boy ";

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

View sourceprint? 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:

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

1 $ str1 = "2 ";

2 $ str2 = "12 ";

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

1 $ str1 = "2 ";

2 $ str2 = "12 ";

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

1 string strstr (string haystack, string needle );
1 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

1 $ 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. ";

2 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

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

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

1 $ 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. ";

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

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

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

1 $ str1 = "hello word ";

2 echo strpos ($ str1, 'o ');

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

1 $ str1 = "hello word ";

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

1 $ str1 = "hello word ";

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

1 $ str1 = "hello word ";

2 $ position = strrpos ($ str1, 'H'); // The first character is found, $ position = 0

3 if ($ position = false ){

4 echo 'not found ';

5} else {

6 echo $ position;

7}

3. Replace the substring: str_replace (), substr_replace ()
The following is a prototype of the str_replace () function:

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

1 $ str1 = "hello word ";

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

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

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

1 $ str1 = "xxx@gmail.com.cn ";

2 if (! Eregi ('[A-Z0-9. _ % +-] + @ [A-Z0-9.-] +. [A-Z] {2, 4}', $ str1 )){

3 echo 'incorrect Email address ';

4} else {

5 echo 'true ';

6}

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:

1 string ereg_replace (string pattern, string replacement, string search );
1 $ str1 = "123123@gmail.com.cn ";

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

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

1 $ str1 = "123123@gmail.com.cn ";

2 $ arr = split ('. | @', $ str1 );

3 while (list ($ key, $ value) = each ($ arr )){

4 echo '<br/>'. $ key. '--'. $ value;

5}

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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.