Monday, September 10, 2012

Learn PHP Preg_match with working Example

preg_match is a wonder ful function of PHP( 4,5,6) to Perform a regular expression match. Its little bit difficult to learn but extremely useful when you properly understand it. Extensively use to extract string in SEO process, in validation of E-mail ID and so its impossible for me to describe its utilization in PHP Development.

Structure :
preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Simplified Version
preg_match(pattern, Subject ,array)
Pattern-  The pattern to search for, as a string. 
like 
xyz@openplus.in 
+91-8564123356
<title>openplus.in</title>

Subject = Variable that contains that value
like
$sanjay='xyz@openplus.in';
Array-  to store extracted value.
For more details visit PHP.net

A Simple Example:
This example extract title from title tags, heavily used is SEO industry.
<?php
$sanjay='<title>Please share this page to twitter, Google Plus and Twitter</title>';
preg_match('/<title>(.*)<\/title>/i',$sanjay,$mt);
echo $mt['1'];
?>

Note : use / to start a pattern and /i to end. Use (.*) to find the desired value.
Above Code will give a out put
Please share this page to twitter, Google Plus and Twitter

PickMe
Delicious Save this on Delicious

6 comments :

  1. Another similar Example of Preg_match with regular expression to validate e-mail id is here
    Validate E-mail id using preg_match and regular expression

    ReplyDelete
  2. Here is how to scrape with pregmatch.
    http://www.bohemiawebsites.com/Scrape-HTML-With-PHP.html

    ReplyDelete
  3. Great post indeed and thanks for all the information, it was very helpful i really like that you are providing information on PHP and MYSQL with basic JAVASCRIPT,being enrolled in http://www.wiziq.com/course/5871-php-mysql-with-basic-javascript-integrated-course i was looking for such information online to assist me on php and mysql and your information helped me a lot. Thanks.

    ReplyDelete
  4. Thanks man for this great post.it saved my day.thanks again budy.i always visit your blog.it always help.
    http://websnube.com/

    ReplyDelete
  5. Thanks for sharing, I will bookmark and be back again



    PHP Course in Chennai

    ReplyDelete
  6. Nice blog...Very useful information is providing by ur blog. find Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete

If you have any Question , Suggestion or idea then please comment regarding the post.