Home > Enterprise >  Preg match regex output https// instead of https://
Preg match regex output https// instead of https://

Time:07-09

I'm not sure how to ask this but I am having a problem with output URL showing https//example.com

Below is my code, someone please i need assistance, I am trying to achieve https://example.com while I got https//example.com

Am i missing anything on the regex or something..?

Thanks.


 shuffle($randurl);

    $smtp_email = $smtp_user;
    $smtp_user = explode("@", $smtp_user) [0];

    $randurls = array_shift($randurl);

    preg_match('@^(?:https://)?([^/] )@i', $randurls, $matches);
    $host = $matches[1];

    $host = explode('.', $host);
    $host = $host[0];

    $email64 = base64_encode($email);
    $base64url = base64_decode($randurls);

    if ($redirect == 1)
    {
        $randurls = "$randurls?email=" . urlencode($email64) . "";
    }
    else if ($redirect == 2)
    {
        $randurls = "$randurls?a=" . urlencode($email64) . "";
    }
    else if ($redirect == 3)
    {
        $randurls = "$randurls?email=" . urlencode($email) . "";    

CodePudding user response:

In regex, colon symbol is used for character classes. Such as [:alpha:] represents an alphabetic character. Your regex is reading (:https:) as a singular expression. I suggest looking over this to get a better idea on handling this. https://www.codexpedia.com/regex/regex-symbol-list-and-regex-examples/ Since I do not actually know what you are trying to achieve, I can not give a more definitive answer on how to get whatever you are trying to get.

CodePudding user response:

Find by http and optional s appended by a colon and keep (replace by) the match without colon.

Note: A preg_match finds a pattern, does not replace it.

$pattern = '/(https?):/';
echo preg_replace($pattern, '$1', 'http://www.example.com'), PHP_EOL;
echo preg_replace($pattern, '$1', 'https://www.example.com'), PHP_EOL;
http//www.example.com
https//www.example.com

CodePudding user response:

You can match the protocol and assert // to the right.

In the replacement use :

\bhttps?\K(?=//)

Regex demo | PHP demo

$re = '`\bhttps?\K(?=//)`';
$str = 'https//example.com';
$subst = ':';

echo preg_replace($re, $subst, $str);

Output

https://example.com

You could also use a capture group, and replace with $1:$2

\b(https?)(//)

Regex demo

  • Related