preg_match(), function preg_match_all(), preg_grep() in PHP

By: Andi, Stig and Derick Emailed: 1646 times Printed: 2120 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

preg_match() is the function that matches one pattern with the subject string and returns either true or false depending whether the subject matched the pattern. It also can return an array containing the contents of the different sub-pattern matches. X Turns on extra features in the PCRE engine. At the moment, the only feature it turns on is that the engine will throw an error in case an unknown escape sequence was detected. Normally, this would just have been treated as a literal. (Notice that we still have to escape the one \ for PHP itself.)

The function preg_match_all() is similar, except that it matches the pattern with the subject repeatedly. Finding all the matches is useful when extracting information from documents. Take, for example, the situation in which you want to extract email addresses from a web site:

<?php

$raw_document = file_get_contents('http://www.w3.org/TR/CSS21');

$doc = html_entity_decode($raw_document);

$count = preg_match_all(

'/<(?P<email>([a-z.]+).?@[a-z0-9]+\.[a-z]{1,6})>/Ui',

$doc,

$matches

);

var_dump($matches);

?>

outputs

Array

(

[0] => Array

(

[0] => <bert @w3.org>
[1] => <tantekc @microsoft.com>
[2] => <ian @hixie.ch>
[3] => <howcome @opera.com>

)

[email] => Array

(

[0] => bert @w3.org
[1] => tantekc @microsoft.com
[2] => ian @hixie.ch
[3] => howcome @opera.com

)

[1] => Array

(

[0] => bert @w3.org
[1] => tantekc @microsoft.com
[2] => ian @hixie.ch
[3] => howcome @opera.com

)

[2] => Array

(

[0] => bert
[1] => tantekc
[2] => ian
[3] => howcome

)

)

This example reads the contents of the CSS 2.1 specification into a string and decodes the HTML entities in it. The script then uses a preg_match_all() on the document, using a pattern that matches < + an email address + >, and stores the email addresses in the $matches array. The output shows that preg_match_all() doesn’t store all sub-pattern belonging to one match in one element of the $matches array. Instead, it stores all the sub-pattern matches belonging to the different matches into one element of $matches.

preg_grep() performs similarly to the UNIX egrep command. It compares a pattern against elements of an array containing the subjects. It returns an array containing the elements that were successfully matched against the pattern. See the next example, which returns all valid IP addresses from the array $addresses:

<?php

$addresses = array('212.187.38.47', '188.141.21.91', '2.9.256.7', '<<empty>>');

$pattern = '@^((\d?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}' '(\d?\d|1\d\d|2[0-4]\d|25[0-5])@';

$addresses = preg_grep($pattern, $addresses);

print_r($addresses);

?>


PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Andi, Stig and Derick
Execution Lifetime of a PHP script
preg_split() and explode() in PHP
preg_replace() and preg_replace_callback() in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
tmpfile() in PHP
Renaming and Removing Files in PHP
Locking files in PHP
File Handling in PHP
Handling BLOB in PHP and MySQL
Using Sessions in PHP
Using Cookies in PHP
Using PEAR::Crypt_HMAC in PHP
Using HMAC Verification in PHP
Input Validation in PHP
__autoload() METHOD in PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
Exception in module wampmanager.exe at 000F15A0 in Windows 8
isset() function in PHP
.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable
Handling BLOB in PHP and MySQL
Reading Cookie Values in PHP
Parent: child process exited with status 3221225477 -- Restarting
Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......
Get the next working day in PHP
Return multiple values from a function in PHP
History and origin of PHP
superglobals in PHP
Assignment operators in PHP
public, protected, and private Properties in PHP
preg_match(), function preg_match_all(), preg_grep() in PHP
Reading contents of a File into a String in PHP
Most Emailed Articles (in PHP)
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Convert XML to CSV in PHP
Using PEAR::Crypt_HMAC in PHP
Password must include both numeric and alphabetic characters - Magento
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Resume or Pause File Uploads in PHP
Comparison operators in PHP
Extract files from a .zip file using PHP
Appending One Array to Another in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
isset() function in PHP
do...while Loops in PHP
Counting Lines, Paragraphs, or Records in a File using pc_split_paragraphs() in PHP