preg_match 如果第一个字符是斜杠
preg_match if first char is slash
我试图找出字符串的第一个字符是否为斜杠。
我有这个字符串/var/www/html
$mystring = "/var/www/html";
$test = preg_match("/^/[.]/", $mystring);
if ($test == 1)
{
echo "ret = 1";
}
else
{
echo "ret = 0";
}
但我总是得到 ret = 0
。
试试这个:
<?php
$mystring = "/var/www/html";
$test = preg_match("/^\//", $mystring);
if ($test == 1)
{
echo "ret = 1";
}
else
{
echo "ret = 0";
}
您只需使用 strpos()
即可:
<?php
$mystring = "/var/www/html";
if(strpos($mystring,"/") === 0){
echo "ret = 1";
}else{
echo "ret = 0";
}
?>
为什么必须使用 preg_match?
你不能用substr吗?
if (substr($mystring, 0, 1) == "/") {
echo "ret= 1";
}
如果这就是您想要做的,那么您也可以这样做:
echo $mystring[0] == "/" ? "ret 1" : "ret 0";
其他功能真的不用用了
您必须在您的模式中转义 /,因为您已经将其用作您的正则表达式分隔符,所以试试这个:
$mystring = "/var/www/html";
$test = preg_match("/^\//", $mystring);
if ($test == 1)
{
echo "ret = 1";
}
else
{
echo "ret = 0";
}
我试图找出字符串的第一个字符是否为斜杠。
我有这个字符串/var/www/html
$mystring = "/var/www/html";
$test = preg_match("/^/[.]/", $mystring);
if ($test == 1)
{
echo "ret = 1";
}
else
{
echo "ret = 0";
}
但我总是得到 ret = 0
。
试试这个:
<?php
$mystring = "/var/www/html";
$test = preg_match("/^\//", $mystring);
if ($test == 1)
{
echo "ret = 1";
}
else
{
echo "ret = 0";
}
您只需使用 strpos()
即可:
<?php
$mystring = "/var/www/html";
if(strpos($mystring,"/") === 0){
echo "ret = 1";
}else{
echo "ret = 0";
}
?>
为什么必须使用 preg_match?
你不能用substr吗?
if (substr($mystring, 0, 1) == "/") {
echo "ret= 1";
}
如果这就是您想要做的,那么您也可以这样做:
echo $mystring[0] == "/" ? "ret 1" : "ret 0";
其他功能真的不用用了
您必须在您的模式中转义 /,因为您已经将其用作您的正则表达式分隔符,所以试试这个:
$mystring = "/var/www/html";
$test = preg_match("/^\//", $mystring);
if ($test == 1)
{
echo "ret = 1";
}
else
{
echo "ret = 0";
}