PHP string "contains"

PhpRegexString

Php Problem Overview


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 (".").

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

You can use these string functions,

strstr — Find the first occurrence of a string

stristr — Case-insensitive strstr()

strrchr — Find the last occurrence of a character in a string

strpos — Find the position of the first occurrence of a substring in a string

strpbrk — Search a string for any of a set of characters

If that doesn't help then you should use preg regular expression

preg_match — Perform a regular expression match

Solution 3 - Php

You can use stristr() or strpos(). Both return false if nothing is found.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionealeonView Question on Stackoverflow
Solution 1 - PhpakatakritosView Answer on Stackoverflow
Solution 2 - PhpMuthu KumaranView Answer on Stackoverflow
Solution 3 - PhpSylverdragView Answer on Stackoverflow