Reputation: 49
Hi I have problem with correct url validation with query string containing email address like:
https://example.com/[email protected]
this email is ofc correct one [email protected]
is an alias of [email protected]
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?
Upvotes: 0
Views: 831
Reputation: 1456
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 protected]&email2=john+test2@exam+ple.com';
echo replace_plus_sign($page);
Gives the following output:
https://example.com/[email protected]&[email protected]
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.
Upvotes: 1