php-regex-for-web-developers

Regular expressions are a very useful tool for developers. They allow to find, identify or replace a word, character or any kind of string. This tutorial will teach you how to master PHP regexp and show you extremely useful, ready-to-use PHP regular expressions that any web developer should have in his toolkit.

Getting Started With Regular Expressions

For many beginners, regular expressions seem 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 of PCRE regex patterns:

Regular Expressions Syntax

A regular expression (regex or regexp for short) is a special text string for describing a search pattern. A regex pattern matches a target string. The following table describes most common regex:

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 “jpg”
[a-z] One or more lowercase letters
[0-9.-] Any 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

PHP has many useful functions to work with regular expressions. Here is a quick cheat sheet of the main PHP regex functions. Remember that all of them are case sensitive.

For more information about the native functions for PHP regular expressions, have a look at the manual.

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. Useful for search and replace.
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() Preg Split (preg_split()) operates exactly like the split() function, except that regular expressions are accepted as input parameters.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regex pattern within a string.
preg_ quote() Quote regular expression characters

Validate a Domain Name

Case sensitive regex to verify if a string is a valid domain name. This is very useful when validating web forms.

$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 will find a specific word in a string and enlight it. Extremely useful for search results. Remember that it’s case sensitive.

$text = "Sample sentence... 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";
echo preg_replace("http://www.webdesignernews.com/b(regex)b/i", '1', $text);

» Source

Enlight Search Results in Your WordPress Blog

The previous code snippet can be very handy when it comes to displaying search results. If your website is powered by WordPress, here is a more specific snippet that will search and replace a text by the same text within an HTML tag that you can style later, using CSS.

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:

',
		$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 wanted 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 case insensitive PCRE regex will be very helpful.

$text = preg_replace("http://www.webdesignernews.com/s(w s)1/i", "$1", $text);

» Source

Remove Repeated Punctuation

Same php regex as above, but this one will look for repeated punctuation within a string. Goodbye multiple commas!

$text = preg_replace("http://www.webdesignernews.com/. /i", ".", $text); 

» Source

Match 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.'[^>]*>(.*?).'}',
                   $xml,
                   $matches,
                   PREG_PATTERN_ORDER);

  return $matches[1];
}

Match an HTML/XML Tag With a Specific 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

113 comments

  1. Hello to every one, it’s in fact a fastidious for me to visit
    this site, it contains precious Information.

  2. Amazing! This blog looks exactly like my old one! It’s on a totally different
    topic but it has pretty much the same page layout and
    design. Wonderful choice of colors!

  3. I am curious to find out what blog system you have been working with?
    I’m having some minor security issues with my latest site
    and I’d like to find something more risk-free. Do you have any suggestions?

  4. It’s appropriate time to make some plans for the future and it is time to be happy.
    I’ve read this post and if I could I want to suggest you some interesting
    things or suggestions. Perhaps you could write next articles
    referring to this article. I desire to read even more things about
    it!

  5. Hey there! Do you use Twitter? I’d like to follow you if that would
    be ok. I’m definitely enjoying your blog and look forward to new posts.

  6. Hello there! I know this is kind of off topic but I was wondering which blog platform are you using for this
    website? I’m getting tired of WordPress because I’ve had
    problems with hackers and I’m looking at options for another platform.
    I would be great if you could point me in the direction of a
    good platform.

  7. My partner and I stumbled over here coming from a different website and thought I might as well
    check things out. I like what I see so now i’m following you.
    Look forward to looking over your web page yet again.

  8. Hi there very cool website!! Man .. Beautiful .. Amazing ..

    I will bookmark your blog and take the feeds also? I’m glad to
    find so many useful information here within the post, we need work out extra techniques in this
    regard, thank you for sharing. . . . . .

  9. It is the best time to make a few plans for the
    future and it’s time to be happy. I have learn this post and if I may I desire to suggest you few interesting things or
    tips. Maybe you can write next articles regarding this article.
    I want to learn even more things approximately it!

  10. Asking questions are actually good thing if you are not understanding anything totally,
    however this article presents nice understanding yet.

  11. Undeniably believe that which you said. Your favorite
    justification seemed to be on the net the easiest thing to be aware of.
    I say to you, I definitely get annoyed while people think about worries that they just
    don’t know about. You managed to hit the nail
    upon the top as well as defined out the whole thing without having side effect , people could take a signal.
    Will likely be back to get more. Thanks

  12. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is fundamental and everything. However think about if
    you added some great visuals or videos to give your
    posts more, “pop”! Your content is excellent but with pics and clips,
    this site could definitely be one of the most beneficial in its field.
    Good blog!

  13. Howdy! I realize this is sort of off-topic but I needed
    to ask. Does managing a well-established blog such as yours require a lot of work?
    I am brand new to operating a blog however I do write
    in my journal daily. I’d like to start a blog
    so I can share my personal experience and feelings online.
    Please let me know if you have any kind of suggestions
    or tips for brand new aspiring blog owners. Appreciate it!

  14. Hello there! Would you mind if I share your
    blog with my zynga group? There’s a lot of
    people that I think would really enjoy your content.
    Please let me know. Thank you

  15. Just desire to say your article is as amazing.
    The clearness in your post is just spectacular and i can assume
    you are an expert on this subject. Well with your permission let me to
    grab your RSS feed to keep up to date with forthcoming post.

    Thanks a million and please carry on the gratifying work.

  16. I’m extremely inspired along with your writing abilities as
    smartly as with the structure to your blog. Is that this a paid topic or did you modify it your
    self? Anyway keep up the nice quality writing, it
    is uncommon to peer a nice weblog like this one today..

  17. Hello there, I do think your site could be having browser compatibility issues.
    When I look at your website in Safari, it looks fine however, when opening in I.E., it has
    some overlapping issues. I simply wanted to provide you with a quick heads up!
    Apart from that, wonderful blog!

  18. Hello my loved one! I want to say that this post is
    awesome, great written and include almost all vital
    infos. I’d like to see more posts like this .

  19. Hi, Neat post. There is a problem along with your site
    in internet explorer, may check this? IE nonetheless is the marketplace chief and a large element of other people will omit your magnificent
    writing because of this problem.

  20. Hello, i read your blog from time to time and i own a similar one and i was
    just curious if you get a lot of spam feedback? If so how do you protect against it, any plugin or anything you can recommend?
    I get so much lately it’s driving me mad so any help is very much appreciated.

  21. It is in point of fact a great and helpful
    piece of information. I’m happy that you just shared
    this useful information with us. Please keep us
    up to date like this. Thank you for sharing.

  22. First off I want to say great blog! I had a quick question that I’d
    like to ask if you do not mind. I was interested to know how you center yourself and
    clear your head before writing. I’ve had a hard time clearing my thoughts in getting
    my ideas out. I truly do enjoy writing but it just seems like the first 10 to 15 minutes are usually lost simply just trying to figure out how to begin. Any suggestions or tips?
    Thanks!

  23. Do you mind if I quote a few of your articles as long as
    I provide credit and sources back to your weblog?
    My website is in the exact same area of interest as yours and my users would really benefit from some of the information you present here.
    Please let me know if this okay with you. Regards!

  24. My family every time say that I am killing my time
    here at web, however I know I am getting experience everyday by reading thes fastidious posts.

  25. Having read this I believed it was very informative. I appreciate you finding the time
    and effort to put this content together. I once again find myself spending a
    significant amount of time both reading and commenting.

    But so what, it was still worthwhile!

  26. I know this web site provides quality depending articles and other
    information, is there any other web page which presents these kinds
    of stuff in quality?

  27. Howdy! I know this is kinda off topic but I was wondering which blog platform are
    you using for this site? I’m getting tired of WordPress because
    I’ve had problems with hackers and I’m looking at alternatives for another platform.
    I would be great if you could point me in the direction of a good platform.

  28. Very good blog you have here but I was wanting to know if
    you knew of any community forums that cover the same topics discussed in this article?
    I’d really love to be a part of community where
    I can get suggestions from other knowledgeable individuals that share
    the same interest. If you have any suggestions, please let me know.
    Thanks a lot!

  29. Hi would you mind sharing which blog platform
    you’re working with? I’m planning to start my own blog in the near future but I’m having
    a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking for something unique.
    P.S Apologies for being off-topic but I had to ask!

  30. Hey There. I found your blog using msn. This is an extremely well written article.

    I will make sure to bookmark it and come
    back to read more of your useful information. Thanks for the post.
    I’ll certainly comeback.

  31. I read this post fully on the topic of the comparison of hottest and
    preceding technologies, it’s amazing article.

  32. Excellent post. I used to be checking continuously this weblog and I’m inspired!
    Very helpful information specifically the ultimate section 🙂
    I handle such info a lot. I was looking for this particular information for a long time.
    Thank you and best of luck.

  33. Hey there just wanted to give you a brief heads up and let you know a few of the pictures aren’t
    loading properly. I’m not sure why but I think its a linking issue.
    I’ve tried it in two different web browsers and both show the same outcome.

  34. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email.
    I’ve got some creative ideas for your blog you might be interested
    in hearing. Either way, great blog and I look forward to seeing it improve over time.

  35. I have been surfing online more than 3 hours as of late, but I by no means found any fascinating article like
    yours. It is beautiful price enough for me. Personally, if all webmasters and bloggers made good content material as you did, the internet can be much more
    useful than ever before.

    Here is my web-site … agen poker pulsa

  36. Please let me know if you’re looking for a author for your weblog.
    You have some really good articles and I think I would be a good asset.
    If you ever want to take some of the load off, I’d
    really like to write some articles for your blog in exchange for a link back to mine.
    Please shoot me an email if interested. Cheers!

  37. My family every time say that I am killing my time here at
    web, but I know I am getting familiarity everyday
    by reading such good articles or reviews.

  38. Thank you for sharing your thoughts. I really appreciate your efforts and I am waiting for your further write ups thank you once again.

  39. I’m really enjoying the design and layout of your blog.
    It’s a very easy on the eyes which makes it much more enjoyable for
    me to come here and visit more often. Did you hire out a developer to create your theme?
    Excellent work!

  40. Hello! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having difficulty finding one?
    Thanks a lot!

  41. Hello there, I discovered your site by way of
    Google even as looking for a related topic, your website came
    up, it seems great. I have bookmarked it in my google bookmarks.

    Hi there, simply become aware of your blog via Google, and located that it’s truly informative.
    I am gonna watch out for brussels. I will appreciate for those who
    continue this in future. Lots of people can be benefited
    out of your writing. Cheers!

  42. I know this web site provides quality based articles or reviews and additional
    stuff, is there any other site which presents such stuff in quality?

  43. Just want to say your article is as astounding.
    The clarity on your submit is just great and that i can suppose you are a professional on this subject.
    Well along with your permission allow me to clutch your RSS feed to keep up
    to date with impending post. Thank you 1,000,000 and please
    continue the rewarding work.

  44. Hmm it looks like your blog ate my first comment (it was
    super long) so I guess I’ll just sum it up what I had written and
    say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to the
    whole thing. Do you have any suggestions for inexperienced blog writers?
    I’d genuinely appreciate it.

  45. Hi, i read your blog from time to time and i own a similar one and i
    was just wondering if you get a lot of spam remarks?

    If so how do you stop it, any plugin or anything you
    can suggest? I get so much lately it’s driving me crazy so any support
    is very much appreciated.

  46. Great blog here! Also your web site loads up fast!
    What web host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

  47. Thanks for any other informative web site. Where else may I
    am getting that type of information written in such a perfect approach?
    I have a undertaking that I am simply now operating on, and I’ve been on the look out for such info.

  48. I know this website provides quality depending content
    and additional information, is there any other web site which presents these kinds of things in quality?

  49. Its like you read my thoughts! You seem to grasp so much about this, such as you
    wrote the ebook in it or something. I believe that you simply can do with some percent
    to power the message house a little bit, however other than that, this is magnificent blog.
    A fantastic read. I will definitely be back.

  50. Hey! I know this is kinda off topic but I was wondering which blog platform are you using for this website?
    I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform.
    I would be awesome if you could point me in the direction of a good platform.

Leave a Reply

Your email address will not be published.