开发者

preg_match: ensure the start and the end contains something

I want to have the regular expression that makes sure the beginning of the string contains 'http://' and '/' and the end.

This is a longer version I came up 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 these two expressions can put together like below, but it wont 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 try to combine must be wrong! any idea?

thanks, Lau


if(preg_match('/^http:\/\/.*\/$/', $site_http)) 
{
  ...
}

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

For example:

<?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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜