Black
Black

Reputation: 20322

preg_match if first char is slash

I try to find out if the first char of a string is a slash.

I have this string /var/www/html

$mystring = "/var/www/html";
$test = preg_match("/^/[.]/", $mystring);

if ($test == 1)
{
    echo "ret = 1";
}
else 
{
    echo "ret = 0";
}

But I always get ret = 0.

Upvotes: 4

Views: 2075

Answers (5)

Andreas
Andreas

Reputation: 23958

Any reason why you have to use preg_match?

Can't you use substr?

if (substr($mystring, 0, 1) == "/") {
  echo "ret= 1";
}

Upvotes: 3

Amit Verma
Amit Verma

Reputation: 41219

You have to escape the / in your pattern, as you are already using it as your regex delimeter, so try this :

$mystring = "/var/www/html";
$test = preg_match("/^\//", $mystring);

if ($test == 1)
{
    echo "ret = 1";
}
else 
{
    echo "ret = 0";
}

Upvotes: -3

Ren Camp
Ren Camp

Reputation: 440

Try this:

<?php
$mystring = "/var/www/html";
$test = preg_match("/^\//", $mystring);

if ($test == 1)
{
    echo "ret = 1";
}
else 
{
    echo "ret = 0";
}

Upvotes: 3

Nijraj Gelani
Nijraj Gelani

Reputation: 1466

If this is all you want to do then you can also do something like this :

echo $mystring[0] == "/" ? "ret 1" : "ret 0";

No need to use other functions really.

Upvotes: 2

mitkosoft
mitkosoft

Reputation: 5316

You can simply use strpos() for that:

<?php
    $mystring = "/var/www/html";
    if(strpos($mystring,"/") === 0){
        echo "ret = 1";
    }else{
        echo "ret = 0";
    }
?>    

Upvotes: 3

Related Questions