Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string "contains" [duplicate]

Tags:

string

regex

php

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

like image 322
ealeon Avatar asked Oct 18 '22 18:10

ealeon


People also ask

How do I find a repeated character in a string in PHP?

php $string = "aabbbccddd"; $array=array($array); foreach (count_chars($string, 1) as $i => $val) { $count=chr($i); $array[]= $val. ",". $count; } print_r($array); ?>

What is array unique in PHP?

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.


2 Answers

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.

like image 495
akatakritos Avatar answered Oct 20 '22 08:10

akatakritos


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

like image 66
Muthu Kumaran Avatar answered Oct 20 '22 06:10

Muthu Kumaran