Search with regular expressions

2

Hello, I would like your help with the following problem, which I have in this code.

    function verificarParametro($loopurl,$urlHost) {
if (preg_match("/(\W|^){$urlHost}(\W|$)/i", $loopurl))
    return true;
    else
    return false;

It checks the url by taking the parameter set to $urlHost and checking on $loopurl , if the value is true, otherwise it is false.

Now here's my problem, I need to do a full check from start to finish of the parameter that was specified in the $urlHost field, even if it has any special characters or any other type of parameter, such as /*+-!|?\: etc.

For example, if I put this to get the parameter below, it will give line error.

if (verificarParametroA('https://drive.google.com/file/d/abcdfghiglmnopqrstuvxz/
', 'drive.google.com/file/d/')) {

    echo 'Sim'; }
    
asked by anonymous 07.06.2018 / 20:29

2 answers

1

Passing the parameter directly into the expression will cause problems:

"/(\W|^){$urlHost}(\W|$)/i"

You should escape the characters with preg_quote ( like quoted by @ W.Faustino with the / > delimiter), another thing is that regex should probably be:

/^(\W|){$urlHost}(\W|$)/i

Because if the ^ sign is not at the beginning a url like this could return TRUE:

verificarParametroA('https://foo.com?u=http://bar.com', 'bar.com')
  

Note that the use of strpos and stripos will also fail

It should look like this (you really do not need an if and else in this case):

function verificarParametro($loopurl, $urlHost) {
    $urlHost = preg_quote($urlHost, '/');
    return !!preg_match("/^(\W|){$urlHost}(\W|$)/i", $loopurl);
}

However I recommend even using the parse_url function, it will extract the necessary data and thus you will be able to do a more precise check like this:

function verificarParametro($loopurl, $urlHost)
{
    $host = parse_url($loopurl, PHP_URL_HOST);
    return strcasecmp($host, $urlHost) == 0;
}
  

Note: I used strcasecmp to compare if both strings are equal independently in case-insensitive

    
07.06.2018 / 21:57
1

If $ loopurl needs to be contained exactly the same within $ urlHost, strpos can be used. Example:

function verificarParametro($loopurl, $urlHost)
{
    return (bool) strpos('https://drive.google.com/file/d/abcdfghiglmnopqrstuvxz/', $loopurl);
}
    
07.06.2018 / 21:09