How do i check if a string contains a specific character in php?

You could use regular expressions as it's better for word matching compared to strpos, as mentioned by other users. A strpos check for are will also return true for strings such as: fare, care, stare, etc. These unintended matches can simply be avoided in regular expression by using word boundaries.

A simple match for are could look something like this:

$a = 'How are you?';

if (preg_match('/\bare\b/', $a)) {
    echo 'true';
}

On the performance side, strpos is about three times faster. When I did one million compares at once, it took preg_match 1.5 seconds to finish and for strpos it took 0.5 seconds.

Edit: In order to search any part of the string, not just word by word, I would recommend using a regular expression like

$a = 'How are you?';
$search = 'are y';
if(preg_match("/{$search}/i", $a)) {
    echo 'true';
}

The i at the end of regular expression changes regular expression to be case-insensitive, if you do not want that, you can leave it out.

Now, this can be quite problematic in some cases as the $search string isn't sanitized in any way, I mean, it might not pass the check in some cases as if $search is a user input they can add some string that might behave like some different regular expression...

Also, here's a great tool for testing and seeing explanations of various regular expressions Regex101

To combine both sets of functionality into a single multi-purpose function (including with selectable case sensitivity), you could use something like this:

function FindString($needle,$haystack,$i,$word)
{   // $i should be "" or "i" for case insensitive
    if (strtoupper($word)=="W")
    {   // if $word is "W" then word search instead of string in string search.
        if (preg_match("/\b{$needle}\b/{$i}", $haystack)) 
        {
            return true;
        }
    }
    else
    {
        if(preg_match("/{$needle}/{$i}", $haystack)) 
        {
            return true;
        }
    }
    return false;
    // Put quotes around true and false above to return them as strings instead of as bools/ints.
}

One more thing to take in mind, is that \b will not work in different languages other than english.

The explanation for this and the solution is taken from here:

\b represents the beginning or end of a word (Word Boundary). This regex would match apple in an apple pie, but wouldn’t match apple in pineapple, applecarts or bakeapples.

How about “café”? How can we extract the word “café” in regex? Actually, \bcafé\b wouldn’t work. Why? Because “café” contains non-ASCII character: é. \b can’t be simply used with Unicode such as समुद्र, 감사, месяц and 😉 .

When you want to extract Unicode characters, you should directly define characters which represent word boundaries.

The answer: (?<=[\s,.:;"']|^)UNICODE_WORD(?=[\s,.:;"']|$)

So in order to use the answer in PHP, you can use this function:

function contains($str, array $arr) {
    // Works in Hebrew and any other unicode characters
    // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
    // Thanks https://www.phpliveregex.com/
    if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
}

And if you want to search for array of words, you can use this:

function arrayContainsWord($str, array $arr)
{
    foreach ($arr as $word) {
        // Works in Hebrew and any other unicode characters
        // Thanks https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed
        // Thanks https://www.phpliveregex.com/
        if (preg_match('/(?<=[\s,.:;"\']|^)' . $word . '(?=[\s,.:;"\']|$)/', $str)) return true;
    }
    return false;
}

As of PHP 8.0.0 you can now use str_contains

(PHP 8)

str_containsDetermine if a string contains a given substring

Description

str_contains(string $haystack, string $needle): bool

Parameters

haystack

The string to search in.

needle

The substring to search for in the haystack.

Return Values

Returns true if needle is in haystack, false otherwise.

Examples

Example #1 Using the empty string ''

if (str_contains('abc''')) {
    echo 
"Checking the existence of the empty string will always return true";
}
?>

The above example will output:

Checking the existence of the empty string will always return true

Example #2 Showing case-sensitivity

$string 'The lazy fox jumped over the fence';

if (

str_contains($string'lazy')) {
    echo 
"The string 'lazy' was found in the string\n";
}

if (

str_contains($string'Lazy')) {
    echo 
'The string "Lazy" was found in the string';
} else {
    echo 
'"Lazy" was not found because the case does not match';
}
?>

The above example will output:

The string 'lazy' was found in the string
"Lazy" was not found because the case does not match

Notes

Note: This function is binary-safe.

See Also

  • str_ends_with() - Checks if a string ends with a given substring
  • str_starts_with() - Checks if a string starts with a given substring
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strstr() - Find the first occurrence of a string
  • strpbrk() - Search a string for any of a set of characters
  • substr() - Return part of a string
  • preg_match() - Perform a regular expression match

scm6079

1 year ago

For earlier versions of PHP, you can polyfill the str_contains function using the following snippet:

// based on original work from the PHP Laravel framework
if (!function_exists('str_contains')) {
    function
str_contains($haystack, $needle) {
        return
$needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}
?>

aisunny7 dot xy at gmail dot com

8 months ago

The polyfill that based on original work from the PHP Laravel framework had a different behavior;

when the $needle is `""` or `null`:
php8's will return `true`;
but, laravel'str_contains will return `false`;

when php8.1, null is deprecated, You can use `$needle ?: ""`;

juliyvchirkov at gmail dot com

1 year ago

// Polyfill for PHP 4 - PHP 7, safe to utilize with PHP 8if (!function_exists('str_contains')) {
    function
str_contains (string $haystack, string $needle)
    {
        return empty(
$needle) || strpos($haystack, $needle) !== false;
    }
}

drupalista dot com dot br at gmail dot com

5 months ago

private function contains(array $needles, string $type, string $haystack = NULL, string $filename = NULL) : bool {
        if (empty($needles)) return FALSE;
        if ($filename)
            $haystack = file_get_contents($filename);

        $now_what = function(string $needle) use ($haystack, $type) : array {
            $has_needle = str_contains($haystack, $needle);
            if ($type === 'any' && $has_needle)
                return ['done' => TRUE, 'return' => TRUE];

            if ($type === 'all' && !$has_needle)
                return ['done' => TRUE, 'return' => FALSE];

            return ['done' => FALSE];
        };

        foreach ($needles as $needle) {
            $check = $now_what($needle);
            if ($check['done'])
                return $check['return'];
        }
        return TRUE;
    }

    function containsAny(array $needles, string $haystack = NULL, string $filename = NULL) : bool {
        return self::contains($needles, 'any', $haystack, $filename);
    }

    function containsAll(array $needles, string $haystack = NULL, string $filename = NULL) : bool {
        return self::contains($needles, 'all', $haystack, $filename);
    }

olivertasche+nospam at gmail dot com

1 year ago

The code from "me at daz dot co dot uk" will not work if the word is
- at the start of the string
- at the end of the string
- at the end of a sentence (like "the ox." or "is that an ox?")
- in quotes
- and so on.

You should explode the string by whitespace, punctations, ... and check if the resulting array contains your word OR try to test with a RegEx like this:
(^|[\s\W])+word($|[\s\W])+

Disclaimer: The RegEx may need some tweaks

AuxData

10 months ago

Until PHP 8 was released, many-a-programmer were writing our own contain() functions. Mine also handles needles with logical ORs (set to '||').
Here it is.

function contains($haystack, $needle, $offset){
    $OR = '||';
    $result = false;

        $ORpos = strpos($needle, $OR, 0);
    if($ORpos !== false){ //ORs exist in the needle string
        $needle_arr = explode($OR, $needle);
        for($i=0; $i < count($needle_arr); $i++){
            $pos = strpos($haystack, trim($needle_arr[$i]), $offset);
            if($pos !== false){
                $result = true;
                break;
            }
        }       
    } else {
        $pos = strpos($haystack, trim($needle), $offset);
        if($pos !== false){
          $result = true;
        }
    }
  return($result);
}

Call: contains("Apple Orange Banana", "Apple || Walnut", 0);
Returns: true

kadenskinner at gmail dot com

1 year ago

$needle

= '@';
$haystack = '';

if (!

str_contains($haystack, $needle)){
echo
'There is not an @ in haystack';
}else{
echo
'There is an @ in haystack';
}

How do I check if a string has a specific character?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do you get a specific value from a string in PHP?

Answer: Use the PHP substr() function The PHP substr() function can be used to get the substring i.e. the part of a string from a string. This function takes the start and length parameters to return the portion of string.

How do you check if a string contains a specific substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

Is there a Contains method in PHP?

The Ds\Set::contains() function is an inbuilt function in PHP which is used to check the given value exists in the set or not.