Preg_match: make sure the start and end contain something

I want to have a regular expression that ensures that the beginning of the line contains "http: //" and "/" and the end.

This is the longer version I came with,

if(!preg_match("/(^http:\/\//", $site_http)) 
{
 $error = true;
 echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start."/>';
}
elseif (!preg_match("/\/$/", $site_http)) 
{
 $error = true;
 echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link has ended with a /."/>';
}

but I thought that these two expressions could be combined as shown below, but this does not work,

if(!preg_match("/(^http:\/\/)&(\/$)/", $site_http)) 
{
 $error = true;
 echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start and a / at the end."/>';
}

the multiple expressions that I am trying to combine must be erroneous! any idea?

thanks lau

+5
source share
1 answer
if(preg_match('/^http:\/\/.*\/$/', $site_http)) 
{
  ...
}

Strength ^http:\/\/from front to http://front, \/$forces a slash at the end, and .*allows everything (and possibly nothing) between them.

For instance:

<?php

foreach (array("http://site.com.invalid/", "http://") as $site_http) {
  echo "$site_http - ";
  if (preg_match('/^http:\/\/.*\/$/', $site_http)) {
    echo "match\n";
  }
  else {
    echo "no match\n";
  }
}
?>

generates the following output:

http: //site.com.invalid/ - match
http: // - no match
+9
source

All Articles