Domanda

I want to see if the current request is on the localhost or not. For doing this, I use the following regular expression:

 return ( preg_match("/(^localhost).*/", $url) == true ||
            preg_match("/^({http|ftp|https}://localhost).*/", $url) == true )
            ? true : false;

And here is the var_dump() of $url:

string 'http://localhost/aone/public/' (length=29)

Which keeps returning false though. What is the problem of this regular expression?

È stato utile?

Soluzione

You are currently using the forward slash (/) as the delimiter, but you aren't escaping it inside your pattern string. This will result in an error and will cause your preg_match() statement to not work (if you don't have error reporting enabled).

Also, you are using alternation incorrectly. If you want to match either foo or bar, you'd write (foo|bar), and not {foo|bar}.

The updated preg_match() should look like:

preg_match("/^(http|ftp|https):\/\/localhost.*/", $url)

Or with a different delimiter (so you don't have to escape all the / characters):

preg_match("#^(http|ftp|https)://localhost.*#", $url)

Altri suggerimenti

Curly braces have a special meaning in a regex, they are used to quantify the preceding character(s).

So:

/^({http|ftp|https}://localhost).*/

Should probably be something like:

#^((http|ftp|https)://localhost).*#

Edit: changed the delimiters so that the forward slash does not need to be escaped

This

{http|ftp|https}

is wrong.

I suppose you mean

(http|ftp|https)

Also, if you want only group and don't capture, please add ?::

(?:http|ftp|https)

I would change your current code to:

return preg_match("~^(?:(?:https?|ftp)://)?localhost~", $url);

You were using { and } for grouping, when those are used for quantifying and otherwise mean literal { and `} characters.

A couple of things to add is that:

  • you can use https? instead of (http|https);
  • you can use other delimiters for the regex when your pattern has those symbols as delimiters. This avoids you excessive escaping;
  • you can combine the two regex, since one part is optional (the (?:https?|ftp):// part) and doing so would make the later comparator unnecessary;
  • the .* at the end is not required.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top