Tyler
Tyler

Reputation: 3813

preg_replace regex requires forward slash open and close?

I'm trying to learn regular expressions. I was testing myself by trying to check an email account. The problem though is it's coming up with an error:

No ending delimiter '^' found in /www/eh11522/public_html/scclib/demo/regex.php on line 8

Here is my code:

<?php
$pattern = "^([\w.]+)@w([\w.]+).([\w.]+)";
$email = "tyler@surazinet";

if (!preg_replace($pattern, '', $subject)) {
echo "worked";
} else {
echo "failed";
}

?>

I found that it will work if I put a slash before and after the pattern, but I don't quite understand what that does, and that doesn't quite match what I want it to.

Upvotes: 2

Views: 1404

Answers (4)

Jacob Eggers
Jacob Eggers

Reputation: 9332

The forward slashes are regex delimiters. You can also use other chars as delimiters such as {pattern}, #pattern#. They are sort of a holdover from other languages such as perl, where you don't need to enclose your regex in quotes for example:

"apples pears oranges" =~ /pears/

They are also used to separate out parts of the regex. For exmaple when you want case interactivity, or to replace some chars: /pattern/replace/flags

//This perl code will replace Earth, earth, eArth... with zeus
"Earth, mars, mercury, pluto" =~ s/earth/zeus/i;

Upvotes: 1

Manse
Manse

Reputation: 38147

The slashes are delimiters and are required changing

$pattern = "^([\w.]+)@w([\w.]+).([\w.]+)";

to

$pattern = "/^([\w.]+)@w([\w.]+).([\w.]+)/";

Will fix your problem. You need to specify a delimiter for the regex. In this case i used / but there are lots of alternatives you can use. Info here on using regular expressions with PHP

Upvotes: 2

Harti
Harti

Reputation: 1520

The slashes are a "masking character" to tell preg_replace() what is the beginning and the end of your regular expression. There are a couple of flags you can put in the very end of a RegEx (i.e. after the second masking character) to make it case insensitive, for instance.

Upvotes: 1

rjz
rjz

Reputation: 16520

Your delimiter doesn't have to be a slash in PHP, but you do need to something to tell the function where the regular expression starts and ends. Both the slash ('/') and hash symbol (#) are popular alternatives; I generally prefer the latter as it allows me to be sloppy when parsing URLs.

$pattern = "#^([\w.]+)@w([\w.]+).([\w.]+)#";

Upvotes: 2

Related Questions