How to ‘convert’ any given regex to a PHP `preg_match`-compatible regex?

Okay, this may be a dumb question, but I’m pretty new to regular expressions and I honestly have no idea how to do this.

I don’t know how to tell if a regex will work with PHP’s preg_match() or not.

For example, I would like to use the following regex with PHP’s preg_match().

# Match the leading part (proto://hostname, or just hostname)
    # ftp://, http://, or https:// leading part
    # or, try to find a hostname with our more specific sub-expression
    (?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # sub domains
    # Now ending .com, etc. For these, require lowercase
    (?-i: com\b
        | edu\b
        | biz\b
        | gov\b
        | in(?:t|fo)\b # .int or .info
        | mil\b
        | net\b
        | org\b
        | [a-z][a-z]\b # two-letter country codes

# Allow an optional port number
( : \d+ )?

# The rest of the URL is optional, and begins with / . . . 
     # The rest are heuristics for what seems to work well
        [.!,?]+  [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]+

preg_match($regex, $url); doesn’t work when the above regex is used as-is. Why not? What are the steps to take here to ‘convert’ it so that it will work?

Note that the regex I’m providing here is just an example; I’d love to learn how to convert any regex to its preg_match-compatible equivalent.

Thanks in advance!

P.S. I’m asking because I’m collecting and comparing different URL regexes on this test page: People keep sending me regexes in other languages, and I don’t know how to make them work :(


You can use the x modifier flag in PHP to allow the use of whitespace and comments. See

Also you need to wrap the regex in a set of delimiters. So /regex/modifiers, like this:


…the i modifier being for case insensitivity.

I highly recommend 3rd edition of Mastering Regular Expressions (3rd edition includes a whole chapter on PHP but the whole book is very enlightening!).

P.S. RegexBuddy (Windows application) can convert regexes between languages for you: Sadly, there’s no Mac version.

Need Your Help

Embedded objects in fixtures raise “unable to find fixtures” errors

ember.js ember-data

I'm using ember-data's fixtures adapter extensively to provide a lot of set-up data in my app. For one model ("Structure"), there is an array of embedded related objects ("Overlays"). When I load a

How to merge two .a files which is built for armv7 and i386?

ios iphone xcode ipad static-libraries

I have 2 static library(.a) files. These 2 files are basically same library.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.