Simple analysis of common regular expression function in PHP

Source: Internet
Author: User

1. Preg_match () function
The Preg_match () function searches for a pattern in a string, returns True if it exists, otherwise returns false

$pattern = '/php/';
$str = ' php100.com ';
Echo Preg_match ($pattern, $STR);

Output results: 1

2. Preg_grep () function
The Preg_grep () function searches all elements in an array, returning an array of all the elements that match a pattern

$pattern = '/p$/';
$strArray =array (' asp ', ' php ', ' jsp ', ' Python ', ' Ruby ');
Print_r (Preg_grep ($pattern, $strArray));

Output Result:
Array
(
[0] + = ASP
[1] + = PHP
[2] + = JSP
)

3. Preg_match_all () function
The Preg_match_all () function matches all occurrences of the pattern in the string, and then puts all matches into the array

$pattern = '/php[1-5]/';
$str = ' PHP1PHP2PHP3PHP4PHP5PHP6PHP7PHP8 ';
Preg_match_all ($pattern, $str, $out);
Print_r ($out);

Output Result:
Array
(
[0] = = Array
(
[0] = Php1
[1] = PhP2
[2] = PhP3
[3] = PhP4
[4] = PHP5
)

)

4. Preg_quote () function
The Preg_quote () function inserts a backslash in each word match either that has a special meaning for the regular expression syntax.

echo preg_quote (' Apple Price is: $5/kg ');

Output: Apple Price is: \$5/kg

5. Preg_replace () function
The Preg_replace () function searches for all matches and then replaces them with the desired string to return

$pattern = '/php[1-5]/';
$str = ' PHP1PHP2PHP3PHP4PHP5PHP6PHP7PHP8 ';

Echo preg_replace ($pattern, ' PHP ', $str);

Output Result: PHPPHPPHPPHPPHPPHP6PHP7PHP8

6. Preg_split () function
The Preg_split () function splits the string in a case-insensitive manner, forming an array of the resulting string and returning

$pattern = '/[\[email protected]]/';
$STR = ' [email protected] ';

Print_r (Preg_split ($pattern, $str));

Output Result:
Array
(
[0] = Feng
[1] = Yingyuan
[2] = Sina
[3] = = com
[4] = cn
)

Simple analysis of common regular expression function in PHP

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.