phpregexpreg-replace

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.


Solution

  • 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