gpt4 book ai didi

php - preg_match : ensure the start and the end contains something

转载 作者:可可西里 更新时间:2023-11-01 13:46:14 25 4
gpt4 key购买 nike

我想要一个正则表达式来确保字符串的开头包含“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."/>';
}

我尝试组合的多个表达式一定是错误的!有什么想法吗?

谢谢,刘

最佳答案

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/ - matchhttp:// - no match

关于php - preg_match : ensure the start and the end contains something,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com