PHP string "contains"

ealeon picture ealeon · Nov 27, 2012 · Viewed 357.5k times · Source

What would be the most efficient way to check whether a string contains a "." or not?

I know you can do this in many different ways like with regular expressions or loop through the string to see if it contains a dot (".").

Answer

akatakritos picture akatakritos · Nov 27, 2012

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.