我希望有一个正则表达式,确保字符串的开头包含'http://'和'/'以及结尾。
这是我提出的更长版本,
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 /."/>';
}
但我认为这两个表达式可以放在一起,如下所示,但它不会起作用,
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."/>';
}
我尝试合并的多个表达式一定是错的!任何想法?
感谢, 刘
答案 0 :(得分:10)
if(preg_match('/^http:\/\/.*\/$/', $site_http))
{
...
}
^http:\/\/
强制http://
位于前端,\/$
强制结束斜线,.*
允许所有内容(可能没有任何内容)。
例如:
<?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";
}
}
?>
生成以下输出:
http://site.com.invalid/ - match http:// - no match