15 PHP regular expressions for web developers

by Jean. 165 Comments -

Regular expressions are a very useful tool for developers. They allow to find, identify or replace text, words or any kind of characters. In this article, I have compiled 15+ extremely useful regular expressions that any web developer should have in his toolkit.

Getting started with regular expressions

For many beginners, regular expressions seems to be hard to learn and use. In fact, they’re far less hard than you may think. Before we dive deep inside regexp with useful and reusable codes, let’s quickly see the basics:

Regular expressions syntax

Regular Expression Will match…
foo The string “foo”
^foo “foo” at the start of a string
foo$ “foo” at the end of a string
^foo$ “foo” when it is alone on a string
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any character that is not a uppercase letter
(gif|jpg) Matches either “gif” or “jpeg”
[a-z]+ One or more lowercase letters
[0-9.-] Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
([wx])([yz]) wy, wz, xy, or xz
[^A-Za-z0-9] Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers

 

PHP regular expression functions

Function Description
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.

preg_ quote() Quote regular expression characters

 

Validate domain name

Verify if a string is a valid domain name.

$url = "http://komunitasweb.com/";
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
    echo "Your url is ok.";
} else {
    echo "Wrong url.";
}

» Source

Enlight a word from a text

This very useful regular expression find a specific word in a text, and enlight it. Extremely useful for search results.

$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
$text = preg_replace("/b(regex)b/i", '<span style="background:#5fc9f6">1</span>', $text);
echo $text;

» Source

Enlight search results in your WordPress blog

As I just said that the previous code snippet could be very handy on search results, here is a great way to implement it on a WordPress blog.
Open your search.php file and find the the_title() function. Replace it with the following:

echo $title;

Now, just before the modified line, add this code:

<?php
	$title 	= get_the_title();
	$keys= explode(" ",$s);
	$title 	= preg_replace('/('.implode('|', $keys) .')/iu',
		'<strong class="search-excerpt">\0</strong>',
		$title);
?>

Save the search.php file and open style.css. Append the following line to it:

strong.search-excerpt { background: yellow; }

» Source

Get all images from a HTML document

If you ever widhed to be able to get all images form a webpage, this code is a must have for you. You should easily create an image downloader using the power of cURL.

$images = array();
preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media);
unset($data);
$data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$media[0]);
foreach($data as $url)
{
	$info = pathinfo($url);
	if (isset($info['extension']))
	{
		if (($info['extension'] == 'jpg') ||
		($info['extension'] == 'jpeg') ||
		($info['extension'] == 'gif') ||
		($info['extension'] == 'png'))
		array_push($images, $url);
	}
}

» Source

Remove repeated words (case insensitive)

Often repeating words while typing? This handy regexp will be very helpful.

$text = preg_replace("/s(w+s)1/i", "$1", $text);

» Source

Remove repeated punctuation

Same as above, but with punctuation. Goodbye repeated commas!

$text = preg_replace("/.+/i", ".", $text); 

» Source

Matching a XML/HTML tag

This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML. Once again, this can be very powerful used along with cURL.

function get_tag( $tag, $xml ) {
  $tag = preg_quote($tag);
  preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}',
                   $xml,
                   $matches,
                   PREG_PATTERN_ORDER);

  return $matches[1];
}

» Source

Matching an XHTML/XML tag with a certain attribute value

This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match <div id=”header”>.

function get_tag( $attr, $value, $xml, $tag=null ) {
  if( is_null($tag) )
    $tag = '\w+';
  else
    $tag = preg_quote($tag);

  $attr = preg_quote($attr);
  $value = preg_quote($value);

  $tag_regex = "/<(".$tag.")[^>]*$attr\s*=\s*".
                "(['\"])$value\\2[^>]*>(.*?)<\/\\1>/"

  preg_match_all($tag_regex,
                 $xml,
                 $matches,
                 PREG_PATTERN_ORDER);

  return $matches[3];
}

» Source

Matching hexadecimal color values

Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.

$string = "#555555";
if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) { 
echo "example 6 successful.";
} 

» Source

Find page title

This handy code snippet will find and print the text within the <title> and </title> tags of a html page.

$fp = fopen("http://www.catswhocode.com/blog","r"); 
while (!feof($fp) ){
    $page .= fgets($fp, 4096);
}

$titre = eregi("<title>(.*)</title>",$page,$regs); 
echo $regs[1];
fclose($fp);

 

Parsing Apache logs

Most websites are running on the well-known Apache webserver. If your website does, what about using PHP and some regular expressions to parse Apache logs?

//Logs: Apache web server
//Successful hits to HTML files only.  Useful for counting the number of page views.
'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?.html?)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'

//Logs: Apache web server
//404 errors only
'^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)404s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'

» Source

Replacing double quotes by smart qutotes

If you’re a typographer lover, you’ll probably love this regexp, which allow you to replace normal double quotes by smart quotes. A regular expression of that kind is used by WordPress on contents.

preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);

» Source

Checking password complexity

This regular expression will tests if the input consists of 6 or more letters, digits, underscores and hyphens.
The input must contain at least one upper case letter, one lower case letter and one digit.

'A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z'

» Source

WordPress: Using regexp to retrieve images from post

As I know many of you are WordPress users, you’ll probably enjoy that code which allow you to retrieve all images from post content and display it.
To use this code on your blog, simply paste the following code on one of your theme files.

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

<?php
$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^>]* />~';

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);

if ( $iNumberOfPics > 0 ) {
     // Now here you would do whatever you need to do with the images
     // For this example the images are just displayed
     for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
          echo $aPics[0][$i];
     };
};

endwhile;
endif;
?>

» Source

Generating automatic smileys

Another function used by WordPress, this one allow you to automatically replace a smiley symbol by an image.

$texte='A text with a smiley :-)';
echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);

 

  • http://www.easigo.co.uk Henry@Nonfault claims

    Just wanna say awesome post. The whole PHP content you showed above really help most of the web developers and help to make their task easy. Me too very thankful to you for this nice post..

  • http://www.itsananderson.com/ Will Anderson

    Hey, I haven’t tested to make sure, but I think the first get_tag function would be broken by the following:


    get_tag('a', '<a title="is a > b?" href="a-gt-b.htm" />Is A > B?</a>');

    The RegEx would match that first > in the attribute and the following text would be returned

    b?” href=”a-gt-b.htm” />Is A > B?

    OK, hopefully none of this comment will be interpreted by WordPress in an unexpected way :)

  • housed

    Hello,
    I don’t undertand how they work. For example if i want that $test don’t have any uppercase letter, how I have to do?

    • http://asdf.com asdf

      strtolower($test);

  • Pingback: 15 PHP regular expressions for web developers | Webs Developer

  • http://alexshapovalov.com/ Alex

    first I would like to say, “great article”. I haven’t used RegEx in quite sometime now, but if I remember correctly “[0-9.-] Аny number, dot, or minus sign” in this example the dot will match anything, if you would like match the dot you have to escape it. please correct me if I am wrong.

  • http://webnevis.net payam

    very nice
    thanks

  • http://www.insidethewebb.com/ Jake Rocheleau

    Sweet article! I’ve seen a lot of Cats Who Code around the web recently, keep up the great posts and I’ll be following along all the way.

  • http://www.wheelchairguide.net Wheelchair Guide

    I am a big fan of regular expressions, because they can make sorting through a bunch of text so much simpler. I wish I had known about them when I first started coding. This is a cool guide and has some great examples!

  • Pingback: 15 PHP regular expressions for web developers « Netcrema - creme de la social news via digg + delicious + stumpleupon + reddit

  • http://cowburn.info Peter C.

    Seems WP has munged up your code (particularly backslash escaping).

  • Pingback: 15 PHP regular expressions for web developers

  • Fred P.

    You mean:

    $text = preg_replace(“/\\.+/i”, “.”, $text);

  • http://www.samuelfolkes.com Samuel Folkes

    Excellent article, I found the code to parse Apache logs and to get all images in a HTML document particularly clever. You did however leave out a very common use for regex that web developers often need to use: validating email addresses.


    $address = 'some email address here';
    $ valid = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
    echo $valid;

    The preg_match() function above will of course evaluate to false. Again, excellent article. I will be putting some of these to use in the near future no doubt.

    • http://www.news-library.com Siddhesh

      Thanks for such nice regex.
      But can I get an regex which will replace text which is enclosed in html comment.

  • http://designblurb.com Sumesh

    That’s a useful list, I recently watched the Themeforest screencast on regex too.

    And to anyone who gets trouble when posting code, just escape them using an encoder like Postable.

  • Toby

    Enlight != word. I’d suggest ‘highlight’ instead.

    @#3 – if you want to make sure that you have only lowercase chars in your string $test, do

    if(preg_match(“/[a-z]/”,$test))
    {
    echo ‘all lowercase’;
    }

  • Toby

    oops – I see that my five second regex doesn’t quite do what you’re asking for – make that

    if(!preg_match(”/[A-Z]/”,$test))
    {
    echo ‘all lowercase’;
    }

  • Pingback: links for 2009-07-27 .:: [aka щямукюшт] Ozver.in | Озверин

  • Pingback: 15 PHP regular expressions for web developers | Ajaxonomy

  • Pingback: 15 PHP regular expressions for web developers « とっても! ちゅどん(雑記帳)

  • http://frederic-soler.fr Fred

    Merci Jean, c’est complet et et très utile.
    Bye.

  • Pingback: Regular Expression for PHP Code – Daily interesting stuffs

  • Yosh

    You forgot to escape dots in some of your expressions.
    A dot is a meta-character to match all characters except newline.

  • http://www.billyboylindien.com Billyboylindien

    Thanks a lot for these tips.
    Very useful.
    Bookmarked

  • Pingback: CatsWhoCode.com: 15 PHP regular expressions for web developers - Kerkness.ca

  • Pingback: CatsWhoCode.com: 15 PHP regular expressions for web developers | PHP

  • Pingback: CatsWhoCode.com: 15 PHP regular expressions for web developers | Webs Developer

  • Pingback: Internet Brain » 15 PHP regular expressions for web developers

  • http://johndturner.com John Turner

    This is an awesome online regex tester. I use it all the time. http://www.spaweditor.com/scripts/regex/index.php

  • Jedaffra

    What do you mean by “enlight” – is that like, highlight?

  • Pingback: All Teched Up « Caintech.co.uk

  • http://www.monica2000.com Monica

    Thanks a lot! Very useful tips and apps! I’ve tried a few already and can’t be more happier.

  • Pingback: links for 2009-07-28 | Jnbn.Org

  • http://www.saynotoflash.com/ Jestep

    Great set of regex’s. Another good one to add would be a decent phone number validation, especially for international #’s, and maybe a clean credit card number validator.

    Anyway, good resource.

  • Pingback: Goonanism » links for 2009-07-28

  • http://dev.pasukan.com Juan Dela Cruz

    Validate domain name is not working.

    Anyone want to correct this regular expression?

    Error: Found:
    Warning: preg_match() [function.preg-match]: Unknown modifier ‘/’ in D:\projects\regex.php on line 3
    Wrong url.

    $url = “http://komunitasweb.com/”;
    if (preg_match(‘/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i’, $url)) {
    echo “Your url is ok.”;
    } else {
    echo “Wrong url.”;
    }

  • Pingback: Waynes Weekly Notable Links | The Bliss of Being

  • http://blogg.tomstone.se Tom Stone

    Regarding the example “Validate domain name” – does that match IDN (Internationalized Domain Name) domains also? Like: www.åäö.se

  • http://ww.jasin.biz Teddy

    Good post!….

    would like to add the following ExtJS regexp form validation that you can simply use for PHP regexp as well http://extjs.com/forum/showthread.php?t=4271

  • http://www.creativeink.co.za Francois Brill

    Nice Post! Thanks

  • http://phil-cook.com Phil Cook

    Hi. Just wanted to say that this is an excellent post. I needed someone to explain clearly the meaning of symbols for reg expressions and this does it with ease. Bookmarked and I will be subscribing to the RSS. Many thanks.

  • http://www.candra.web.id candra

    I love this post…. very useful thx

  • Pingback: 15 expresiones regulares en PHP para desarrolladores - tikitak-o-rama

  • http://www.aldrinponce.com aldrin

    very great post! anyway this is very useful in some projects, specially for web scrap :) I use to work most this things for a year but suddenly I getting bored..

  • Pingback: 15 PHP regular expressions for web developers « Illuminations

  • Bilge

    Super cool story, bro. None of these examples actually work since all backslashes have been stripped.

  • http://kornrunner.net Boris Momcilovic

    Following one is wrong:

    Remove repeated punctuation
    Same as above, but with punctuation. Goodbye repeated commas!

    $text = preg_replace(“/.+/i”, “.”, $text);

    You’re replacing any number of any not a line break character with a dot. If you wished to replace dots, you must escape it first like:

    $text = preg_replace(“/\.+/i”, “.”, $text);

    Or if you wanted to replace multiple commas, put commas (no escaping needed).

  • Pingback: Michael Doyle’s Blog » PHP - Regular Expressions

  • Pingback: 15 PHP Regular Expressions for Web Developers | Choose Daily

  • http://gaarai.com/ Chris Jean

    It looks like a number of the regex strings were modified when you copied and pasted them. Primarily, the backslashes were dropped. For example, you have “/s(w+s)1/i” for the remove repeated words regex when it should be “/\s(\w+\s)\1/i”. Repeated punctuation, hexadecimal color values, smart quotes, password complexity, and probably some others that I missed all have this problem.

  • http://www.jimhanifen.com Jim Hanifen

    Love seeing a post not just about regular expressions, but actual usage and examples. Thanks for the post.

  • Pingback: 15 PHP regular expressions for web developers « HUGO TORRES

  • Pingback: David Rios (dfrios) 's status on Wednesday, 29-Jul-09 20:56:35 UTC - Identi.ca

  • http://www.sweetpixels.co.uk Sahus Pilwal

    Agree great post for the simple fact you post snippets of code and use real world examples. The replace smiley exmaple is the most useful I think!? ;-) Thanks for the information!

  • Pingback: Regular Expression to Get All Image URLs From a Page

  • cole

    Enlight…highlight…what’s the difference. I’m just a stupid American and I knew what he meant. I’m pretty sure that if I had to, I would have chosen the wrong french word, or tense, or gender…whatever. Good post – simplest, most useful summary of regex I’ve ever read. Thanks.

  • Pingback: عبور » Blog Archive » عبارات باقاعده

  • http://Indika.info Indika

    Thanks for the great article.

  • Pingback: PHP regular expressions for web developers |   Indika's Web Log

  • Mattias

    Can you please go through the expression for Validate domain name?
    I also got the error =
    Warning: preg_match() [function.preg-match]: Unknown modifier ‘/’

  • CurtainDog

    Matching XML tags won’t work if you have similar nested tags. XML in general is quite evil.

  • http://www.lkkreplica.com lkkreplica

    Regular expressions make it more easy for the developers!

  • http://royalvacationstravel.com Maxx Buwaya

    Thanks a lot! Very useful tips and apps! I’ve tried a few already and can’t be more happier.

  • Pingback: BlogBuzz August 1, 2009

  • Zecc

    In your domain name validation, you got something like this: :?(d+)?
    I assume it’s meant to validate a port number?

    It should be instead be like this: (:\d+)
    Otherwise it would match a single colon without a number following it.
    Also note there was a backslash missing before the d.

  • http://criterioweb.com Diego

    Very Usefull! Thanks

  • http://epicalex.com/ Epic Alex

    Fantastic article. I was wondering though, any ideas why a preg_replace might not work with the_excerpt, and what could I do to make it work?

  • Pingback: WebDev Weekly #31 | ASAP - As Simple as Possible

  • http://www.php-meets-seo.com Syntaxerror

    Cool – thanks for yout work.

  • Pingback: 15 PHP regular expressions for web developers « I.T News & Stuff

  • Pingback: 17 PHP Practices That Should Be Banished Forever

  • Pingback: Best of the Web- July | Web Tutorials

  • http://www.reviewsarena.com Milch

    Hi! Pretty nice list of regular expressions. Could be useful. Will check again when i will need them. I also check your blog and there are a lot of useful posts.

  • Pingback: Best of the Web- July - Programming Blog

  • Pingback: Best of the Web- July - Programming Blog

  • Pingback: Best of the Web- July « Webby Tutos

  • Pingback: Best of the Web- July | Webby Tutos

  • http://www.zamshed.info Zamshed Farhan

    I am really surpried by getting this collections of regular expressions, It’s really very helpful.

  • Pingback: Expressões Regulares para Desenvolvedores WEB | WEB COM FARINHA

  • Pingback: Best of the Web- July : Webby Tutos

  • Pingback: Daily Digest for 2009-08-07 | Pedro Trindade

  • Pingback: 15 PHP regular expressions for web developers « gdhanasekar

  • http://www.astanda.com Pavel Golovko

    Validate domain name regular expression:

    (?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))

  • TxRx

    Superb post, bookmarked for sure !
    Nice one!

  • http://www.joyoge.com/ joyoge designers’ bookmark

    helpful codes, thanks for the list..

  • http://techpp.com/ Raju

    How much ever I try, they just don’t seem to get into my head :|
    will bookmark and read again

  • http://www.behindthedot.net Ed R

    Thanks for this post. It’s surprising that many developers don’t really understand the full potential of regular expressions. They write elaborate functions to extract items of data, which can be done with a one line RE!!!

  • Pingback: Best of the Web- July :: CSS :: WEBDESIGN FAN

  • Pingback: 15 Very Useful PHP Tutorials

  • http://www.webhost-guru.com Mark

    Thanks, a really great article. I already bookmarked this page.

  • http://www.9636.org Mark

    thanks for your information.it is very helpful for me!
    thanks

  • Pingback: 15 PHP regular expressions for web developers « Alicia Wilkerson

  • Pingback: # 15 PHP regular expressions for web developers | AbhinavZone

  • Pingback: PHP Regular Expressions Syntax, Functions & Cheat Sheets

  • Pingback: Wordpress Blog Services - Getting Started with PHP Regular Expressions

  • Pingback: Getting Started with PHP Regular Expressions | SeanBurdick

  • Pingback: Enver Salih Yaylacı » düzenli ifadeler ve php ( regular expression in php ) - makale derlermesi

  • Jamie Bicknell

    #9 Matching hexadecimal color values the regex doesnt work for all hexadecimal codes, for examble numeric ones, and alpha numeric. I suggest that this regex is used instead:

    To Validate a Hexadecimal Colour, with or without the #
    /^(#)?([0-9a-f]{1,2}){3}$/i

    To Validate a Hexadecimal Colour, WITH #
    /^#([0-9a-f]{1,2}){3}$/i

    You could use this to replace colours in a string via:
    $str = ‘#6699CC and #00ff44 and #ff0000′;
    echo preg_replace(‘|#([0-9a-f]{1,2}){3}|i’,’$0′,$str);

  • Pingback: Getting Started with PHP Regular Expressions - Programming Blog

  • http://progesteronedeficiency.net Rachel

    That sure cleared some things up! Thanks a lot, keep writing stuff like that. I`m in here on a regular basis just to learn. =)

  • Pingback: 15 PHP regular expressions for web developers | TopRoundups

  • http://becometaller.net/becometaller John

    Great info, sure cleared some things up. Guess I still got a couple of things to learn, though. Thank you.

  • Lo.J

    Matching a XML/HTML tag: example does not work, same problem on the source website.
    copy/paste is ok. copy/paste+test is better.
    But i have no anger. Let the light of love shine upon your soul.

  • http://davidwinstead.com David Winstead

    I use Regular Expressions everyday, could not function without them. Great list by the way!

  • Pingback: 17 PHP Practices That Should Be Banished Forever « Technology Strategy Center

  • http://www.reliablewebhosting.us/ RWH

    Highly informative and useful post. This would be a great reference guide to any web developer out there from beginner to advanced level. All I can say is, “Bravo”!

  • http://www.waspnestremoval.co.uk Craig

    This is useful stuff, will be bookmarking this page!
    Has anyone got a good introduction to php page to look at?

  • Pingback: Alex Volkov » Архив » Полезные регулярки.

  • http://www.faceblogger.com/ Mark

    How can I do this?

    Consider the following sms header

    To: #
    Modem: GSM1
    Sent: 09-09-21 13:25:39
    Message_id: 69
    IMSI: 413022600405030

    I need to get the Message id (number only)

    Please help me to do it…

  • http://www.web-optimizer.us/ sunnybear

    TItle regular expression is incorrect. TITILE tag can have a number of attribues (i.e. lang), so the right one will be the following:
    $titre = eregi(“]*>(.*)”,$page,$regs);

  • Hans Zena

    Wonderful list. Here is a very useful regex tester for PHP.

    www.pagecolumn.com/tool/pregtest.htm

  • http://codeguru.services.officelive.com/default.aspx web developer

    I am having a weird problem with Regex to validate domain names. I am using the following expression “/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i”
    It works fine the first time the user same this regular expression. But if the user saves the same expression the next time, it stops working. Also if I check the expression at this point all the back slashes \ are missing from the expression. What could be the problem.

  • http://www.carwaxes.co.uk Chris ward

    Great blog post, exactly what i was looking for and has saved me time figuring it out for myself. Reg-ex is a specialist subject all on its own

  • http://snilesh.com neel

    Excellent Article. I learned alot from this article. I was always scared learning regular expressions. but from your article i learned it easily.

  • Pingback: Regular Expressions : Enterprise Research Systems

  • Tim

    This looked like such a great reference. Until I tried copy and paste of one of the code snippets. Then read the comments and realized that some might not work. Not the author’s fault, I’m sure, but it’s disappointing nonetheless it’s been this long and he hasn’t been back to rectify the fault. Another waste of time.

  • Pascal

    Remove repeated punctuation is kinda stupid, if you don’t escape the dot. (;

  • http://www.rmauger.co.uk Ryan Mauger

    I looked forward to reading this post when I saw smashing-mag tweet about it… but I must say I’m quite disappointed to see regular expressions being used for some of the tasks you have outlined.

    The opening was quite good, but I have to note, you missed than \w can replace “a-zA-Z0-9_” and \d for 0-9, but those are quite forgivable oversights.

    Immediatly I’m confronted with a regex to validate a domain name, which fails! it does nothing to check the validity of the top level domain (this would be an enormous regex, which is why regex’s are not recommended for this task), not to mention not being able to copy with new punycode domains.

    The next problem is, using regular expressions for parsing a html document? this is madness. regular expressions are hugely inefficient for this task. If you wish to grab a title, all the a tags, all the img tags, or query a HTML dom for an attribute, use a proper DOM parser. There is a fantastic one built into PHP, called DOM.

    And the last gripe, using a regex to parse an apache log. This is just silly. an apache log could be quite huge. You should write a proper parser for the task, and parse the log through a stream, and not be using a regex against the whole log. Using a regex for this task is going to eat a huge amount of memory, and be slow as hell!

    I’m sorry that these complaints are strongly worded, but you have a huge audience here, you should be doing a much better job than this. People will not advance as coders without pointing in the RIGHT direction, this is taking them off at a tangent they will need to unlearn in the future!

    There are some valid usecases for regular expressions in this post, removing repeated words, doubled punctuation, and even swapping in smileys, but Its sad to see the rest on a post in a site like this. shame on you!

    • http://www.wprecipes.com Jean-Baptiste Jung

      Thanks for the input Ryan. I agree that some items of this posts are “quick and dirty”, such as the “Parse apache log” regexp. Thanks for pointing it out, comments like yours are useful in order to enhance the site quality.

  • Pingback: VaxCave » Daily links for March 01, 2010

  • jackfuchs

    The above comment from Ryan Mauger is a good starting point regarding the contents of this post.

    Stupid regular expressions, miserable code (PHP). Such a bad post.

    You copied the contents for this post from across the web, without having an idea on what bullshit you are spreading, did you?

    “15+ extremely useful regular expressions that any web developer should have in his toolkit”

    Sorry, but it’s embarrassing.

    • http://www.wprecipes.com Jean-Baptiste Jung

      Ryan Mauger explained why he didn’t liked the post, which is a good thing. Too bad you didn’t. If you have better regexp, I’ll be happy to publish them, feel free to share.

    • http://www.rmauger.co.uk Ryan Mauger

      Im sorry, but I did not mean to start any sort of flaming here. merely to voice my disappointment. There is no need to be insulting in the way you are here.

      Jean-Baptiste generally does a good job on this site, and hopefully my comments will push him to improve his quality. Comments like yours will only strive to anger and upset, and achieve nothing.

  • Pingback: links for 2010-03-02 | Widmann Martin Blog

  • Pingback: Bookmarks vom 02.03.2010

  • Pingback: Espressioni regolari PHP: un’ottima collezione! | Edit - Il blog di HTML.it

  • Pingback: uberVU - social comments

  • http://charlesstover.com Charles Stover

    ^[a-zA-Z0-9_]{1,}$
    Any word of at least one letter, number or _

    What is this about? Whatever happened to ^\w+$

    • jackfuchs

      :o) 1+

  • Pingback: » ce que j’ai vue depuis mon retour ! oxynel, blog communication - Agence de communication Montpellier

  • Pingback: 10+ regular expressions for efficient web development

  • Pingback: Le petit journal du web #3 — Spécial CSS3 (et miscellanées)

  • Justin

    To all of you who get : Warning: preg_match() [function.preg-match]: Unknown modifier ‘/’

    Simply replace the first ” / ” and last ” / ” (before the “i”) of the pattern (in the preg_match) with the symbol ” # “.

    So the first line of the condition should give you this:

    if (preg_match(‘#^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?#i’, $url)) {

    The regex in itself is not too efficient, but if you think it will be enough for your website, just copy/paste my modifications.

  • Pingback: Learning Regular Expressions | developingElegance();

  • Pingback: PHP Helps | The Michaeldon Roareth! - Mad rantings of an undiscovered dinosaur

  • Pingback: 15 PHP Regular Expressions For Web Developers | PHPprogramátor.info

  • Ipsita

    Can any one please help me to solve my problem?
    I have more than one label tags () with same class name but different id in my template file.
    Ex:
    I am here
    Asking for help
    like this.

    The data given is only the class name.(Here in the example class name is “user_home_tpl_html”)
    The pattern of the value of the id attribute is id with an integer.(such as id1,id2….id200…id333)

    Now I need the regular expression to get the content of the label tag
    (Here in the example
    1: I am here
    2: Asking for help
    )

    I’ll be obliged if anybody will be interested to help me

  • Floris

    for the record: document.images fits best if you need to have all images. It is way faster than using regexes.

    the example on this page only fits if you want to retrieve all images from a different page than the one that is currently loaded

  • http://www.endless-loving.com Sebastian

    That is really useful! Many thanks! :)

  • http://none flimh

    Practice REGEX by running this PHP snippet

    CUT-PASTE-RUN
    ————————-
    <?php
    echo '’;
    echo ‘Enter sample straing: ‘;
    echo ‘Enter match pattern: ‘;
    echo ”;
    echo ”;

    if($_POST)
    {
    $string = $_POST['sampleString'];
    $cclass = $_POST['matchPattern'];
    }

    if(preg_match(“/$cclass/”,$string))
    {
    echo ‘Old string: ‘.$string.”;
    echo ‘Match pattern: ‘.$cclass.”;
    $string = preg_replace(“/$cclass/”,’*’,$string);
    echo ‘New string: ‘.$string.”;
    }
    else
    echo ‘No match’;
    ?>

  • http://www.brettwidmann.com Brett Widmann

    So helpful! I’ve tried a few and they work really well.

  • http://www.orthosherbrooke.com Derek Ashland

    I got to show off my knowledge in class because of your post. Now people think I’m a PHP God!

  • alex

    Thanks for the post. Very useful.

    A little fix, maybe: ‘/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i’

    “://” => “:\/\/” (requires escaping
    in the end )?/?/i

    should be: ?/i

    so: ‘/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/i’

    above produces no error.

    Thanks for the useful post, once again!

  • http://ifandbut.com Rick

    Hello,

    Very nice post, it helped us to give example for starter . I have used your post as example for those who want to get first glimpse of regex in PHP.

  • http://muzikki.com nikk

    Hi,
    I got some code that i would like to locate and replace certain text that determine width and height of a youtube video programmatically. I got this youtube code:

    I would like to locate all instances of width and height and change these to lets say (height=200 and width=”400″) so the code would read like this:

    Any assistance would be greatly appreciated.

  • http://techstates.com Syler

    Use this for domain name with port path and query to verify it.

    $hostRegex = “([a-z\d][-a-z\d]*[a-z\d]\.)*[a-z][-a-z\d]*[a-z]“;
    $portRegex = “(:\d{1,})?”;
    $pathRegex = “(\/[^?#\"\s]+)?”;
    $queryRegex = “(\?[^#\"\s]+)?”;
    $urlRegex = “/(?:(?<=^)|(?<=\s))((ht|f)tps?:\/\/" . $hostRegex . $portRegex . $pathRegex . $queryRegex . ")/";

  • http://www.onlinesurveys.co.uk/ Tom

    Good tips. I’ve still got a long way to go, but I’ve finally decided PHP is the language for me. Fingers crossed within a few months I’ll understand what all of these mean better! Tom

  • http://www.rkirmizi.org Recep Kırmızı

    (gif|jpg) Matches either “gif” or “jpeg”

    this does not match jpeg, it will match gif or jpg. just a little typo i guess.

  • http://www.bigfatdiary.com Dana

    what if I want to store (save) all the title and links from the first page in a file (test_google.csv) when I search on google the word “test” ? How should I write the condition and the preg_match_all.

    this is how I extract and post the data:
    $curl = new Curl (true, “cookieFile.txt”);
    $googlePage = $curl -> get(“http://…………”);
    print $googlePage; die ();

  • Bridget

    Great article!! To the point! Every other article I find to try and understand regex STILL makes it sooo hard! :)

  • http://www.150dpi.com suresh

    this is cool. thanks dude.

  • http://www.pure-tentation.fr syndrael

    Great article but for HTML or XML, i really prefer DomDocument.. Easier and more dedicated.
    S.

  • Mohammad Faisal

    I want to check whether the string contains only numbers or not. Like verifying the mobile number.
    what will be the code snippet?

  • http://www.springedge.com Bhavana

    How to extract ” 4 Valid 10-digit number(s) are recorded!! ” form string “ pls help

  • http://www.mgscreativa.com Martin

    Great function “Matching an XHTML/XML tag with a certain attribute value”

    In my case i had to retouch the return by this return $matches[3][0];

    Adding [0] because I wanted the string.

    I used like this and worked!
    $contents = file_get_contents(‘http://site.com/page.php’);
    echo get_tag(‘id’, ‘spamID1, $contents, ‘span’);

  • http://nah chris

    I wanted to use preg_split() and test for either a / or a – or a .

    $splitDate= preg_split(‘[/-.]‘, $mydate);

    I will not work, it will only work with ONE arguement
    $splitDate= preg_split(‘[/]‘, $mydate);
    $splitDate= preg_split(‘[-]‘, $mydate);
    $splitDate= preg_split(‘[.]‘, $mydate);

    why is this? any answers gratefuilly recieved.

  • http://www.phronzs.com Virneto

    Boy, what a wonderfull post this was for me!!!
    Thanks a lot for the explanation and for the code examples!!!

    and best regards to you!

    Virneto

  • Kasun

    How am I catch html tag like follow

  • http://www.displacednames.com/ Junaid Ahmed

    nice and well done.
    great collection.

  • Nicky

    all..

    great post! thank you!
    i need following solution…
    using
    $name2 = preg_replace(“[[0-9]{4}]”, “”, $name );

    this works fine when i have:
    nicky2547
    but when i have nickyA12213
    how to get that work that ONLY last 4 digits will be replaced… to get nickyA1 as result and not nickyA3.

    thank you in advance and wish you a marry christmas!

  • dfgdfg

    gfdgdfg

  • Guilherme A. Zimmermann

    Nice tricks dude! I’m also a animal-friendly web developer ^^ Let’s keep contact. See you!

  • Ahhou

    Goog Work thks !

  • Nanna Barnabas

    some crazy regex. will try some of the examples. thanks