Search code examples
phpposix-ere

How to convert a tricky ereg_replace to preg_replace?


I know there are lots of questions on that but i didn't found anything matches with my question. I want to convert this expression to preg_replace:

$a = ereg_replace('[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*','', $a);

so far tried those but didn't worked:

$a = ereg_replace('/[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*/','', $a);
$a = ereg_replace('|[-a-z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*|','', $a);

Here is the error message for second line:

Warning: preg_replace(): Unknown modifier '}' in

Solution

  • for the character that delimits the match string, use something that's not in the match string, or escaping the uses of the delimiter within the string, like

    $a = ereg_replace('/[-a-z0-9!#$%&\'*+\/=?^_`{|}~]+@([.]?[a-zA-Z0-9_\/-])*/','', $a);
    

    That particular example is kind of hard to read; I'd find a character that's not used at all.