Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match Delimiter error

Good day, I have read about 25 different articles talking about adding a "/" or a "~" etc.., for a delimiter but to no avail with this line of code. Everything I have tried it still gives me a delimiter error. Any help would be greatly appreciated. Thank you for your time. Below is the original code which caused all of my research.

$allowedHosts = array();

// self
$host = $_SERVER['HTTP_HOST'];
if( preg_match('\d+\.\d+\.\d+\.\d+', $host) ) {
    $allowedHosts[] = $host;
} else {
    $allowedHosts[] = '*.' . $host;
    $allowedHosts[] = $host;
}
like image 567
Mark Ellis Avatar asked Dec 01 '25 10:12

Mark Ellis


1 Answers

You need delimiters around the regular expression:

if( preg_match('/\d+\.\d+\.\d+\.\d+/', $host) ) {

In this case I used / which is pretty standard. But you could use other symbols:

if( preg_match('@\d+\.\d+\.\d+\.\d+@', $host) ) {

A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

I assume from looking at your regex you are trying to match an IP address, you could try this instead:

$IP = "198.168.1.78";
if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)) {
    echo "Your IP address is ok.";
} else {
    echo "Wrong IP address.";
}
like image 53
Petah Avatar answered Dec 03 '25 00:12

Petah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!