onatm
onatm

Reputation: 846

The meaning of special characters in Regex

I have been digging codeigniter for some hours. I found some different regex in router class.

preg_match('#^'.$key.'$#', $uri);
preg_replace('#^'.$key.'$#', $val, $uri);

i made a test php file as below:

<?php

$route['login'] = 'user/login';
$route['user/([a-zA-Z-]+)'] = 'user/profile/$1';

$uri = 'user/asfd';

foreach ($route as $key => $val)
{
    if (preg_match('#^'.$key.'$#', $uri))
    {
        echo preg_replace('#^'.$key.'$#', $val, $uri);
    }
}

it correctly gives

user/profile/asfd

What i don't get here is the usage of #^ and $#. I've crawled the web to find some explanation but no luck.

Upvotes: 0

Views: 228

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270677

In this instance, the beginning and ending # are the regular expression's delimiters. You've probably seen them before as /, but many different characters can be used. They merely signify the beginning and end of the regex pattern, and may be followed by additional regex options, like case-insensitivity (i), global matching (g), etc (though preg_match_all() is used instead of the g flag in PHP)

So, the actual pattern being matched is ^$key$. That is, the beginning of the string to match, the value of $key, and the end of the string.

The likely reason for selecting # instead of / as delimiters in this expression is that it eliminates the need to escape the URI pattern's slashes with \.

Upvotes: 5

outis
outis

Reputation: 77420

They're regex delimiters, as explained in the PHP manual. The preg_* functions come from the PCRE (Perl Compatible Regular Expression) library. Perl supports literal regexes, using regex delimiters rather like how strings use single and double quotes. PHP doesn't support literal regexes, but the library still requires the delimiters.

Upvotes: 2

Related Questions