phpregexurlemail-validationurl-validation

Validate url with query string containing email address using PHP


Hi I have problem with correct url validation with query string containing email address like:

https://example.com/?email=john+test1@example.com

this email is ofc correct one john+test1@example.com is an alias of john@example.com

I have regex like this:

$page = trim(preg_replace('/[\\0\\s+]/', '', $page));

but it don't work as I expected because it replaces + to empty string what is wrong. It should keep this + as alias of email address and should cut out special characters while maintaining the correctness of the address.

Example of wrong url with +:

https://examp+le.com/?email=example@exam+ple.com

Other urls without email in query string should be validating correctly using this regex

Any idea how to solve it?


Solution

  • I think this is what you looking for:

    <?php
    
    function replace_plus_sign($string){
        return
        preg_replace(
            '/#/',
            '+',
            preg_replace(
                '/\++/i',
                '',
                preg_replace_callback(
                    '/(email([\d]+)?=)([^@]+)/i',
                    function($matches){
                        return $matches[1] . preg_replace('/\+(?!$)/i', '#', $matches[3]);
                    },
                    $string
                )
            )
        );
    }
    
    $page = 'https://exam+ple.com/email=john+test1+@example.com&email2=john+test2@exam+ple.com';
    echo replace_plus_sign($page);
    

    Gives the following output:

    https://example.com/email=john+test1@example.com&email2=john+test2@example.com
    

    At first, I replaced the valid + sign on email addresses with a #, then removing all the remainings +, after that, I replaced the # with +.

    This solution won't work if there's a #s on the URL if so you will need to use another character instead of # for the temporary replacement.