Check if char is in string php

How to check if a PHP string contains a substring?

In this short tutorial, we look at how to check if a string contains a substring in PHP. We also take a look at the other relevant string manipulation methods in PHP. This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts. However, in case you are here only for the solution use this link.

Table of Content

Why check if a PHP sting contains a substring?

Similar to other programming languages, it is a common practice to check if a string contains a substring. This could be for numerous reasons, subsequently, they are a few inbuilt functions that we could use to check if a PHP string contains a substring. The PHP string contains ( str_contains ) is one of the most commonly used methods, however, the methods you chose would large me decided based on your use cases.

If you are looking to just check if a PHP string contains a substring your can used the str_contains function. if you are looking to check if a PHP sting contains a substring and returns its index you could use the stripos and strpos methods. With that out of the way let us look at all the methods in depth.

Using str_contains :

The str_contains is a new function that was introduced in PHP 8. The str_contains method is used to determine if a PHP string contains a substring. The function checks the string and returns a boolean true in case it exists and false otherwise. However, keep in mind that str_contains is case sensitive.

Syntax of PHP str_contians :

str_contains(string, substring) 

Parameters:

string — Required, the original PHP string that you are looking to search

substring — Required, the substring that you are looking to check if the PHP string contains

Code & Explanation:

 $string = "Hire the top 1% freelance developers" if (str_contains($string, 'Hire'))  echo "PHP string contains 'Hire'"; > else  echo "PHP string does not contain 'Hire"; > ?> //Output: "PHP string contains 'Hire'" 

As the str_contains returns true or false by placing it inside an if. however, the str_contains methods is case sensitive and return false in case the PHP string contains the substring in a different case. Here is an example.

 $string = "Hire the top 1% freelance developers" if (str_contains($string, 'hire'))  echo "PHP string contains 'Hire'"; > else  echo "PHP string does not contain 'Hire"; > ?> //Output: PHP string does not contain 'Hire" 

However, in case you aren’t aware of the case of the substring you could use the strtolower() function.

Using stripos , strpos and strrpos

In case you are looking to check if a PHP string contains a substring, and to find its index these methods are your solutions. The stripos method checks if a PHP string contains a substring, and return the index of the first occurrence of the substring. However, the stripos method is case-insensitive, and if you are looking to case-sensitively check if a PHP string contains a substring you can use the strpos methods. And lastly, strrpos unlike the previous two, this method returns the last occurrence of the substring in the original PHP string.

Syntax of stripos , strpos and strrpos

//Syntax of stripos stripos(string, substring, start) //Syntax of strpos strpos(string, substring, start) //Syntac of strrpos strrpos(string, substring, start) 

Parameters:

string — Required, the original PHP string that you are looking to search

substring — Required, the substring that you are looking to check if the PHP string contains

start — Optional, specific where the search for the substring should begin

Returns:

When used to check if a PHP string contains a substring all the three methods return an index between 0 to n-1 returns false if the substring is not found.

However, given that 0 is also a falsy value remember to use the identical or not identical operator === or ! == and not the equal to operator == as 0 also would be considered as false . You can refer to the code below.

Code & Explanation:

 $string = "Hire the top 1% freelance developers" $substring_index = stripos($string, "Top"); if($substring_index !== false)  echo "'Top' is a substring!"; > if($substring_index !== false)  echo "'top' is a substring!"; > // Output = 'Top' is a substring! // Output = 'top' is a substring! ?> 

As stripos is case insensitive, it does not return a false when used to check if the PHP string contains the ‘Top’ substring. However, this is not the case when strpos or strrpos are used. Now let’s look at a case where the index is 0 .

 $string = "Hire the top 1% freelance developers" $substring_index = stripos($string, "Top"); if($substring_index != false)  echo "'Hire' is a substring"; > else  echo "'Hire' is not a substring"; > //Output = "'Hire' is not a substring" if($substring_index !== false)  echo "'Hire' is a substring"; > else  echo "'Hire' is not a substring"; > //Output = "'Hire' is a substring" ?> 

As you can see the initial ! = operator considers 0 as false this is why it is important to your the identical operators.

Limitations and Caveats

  • Which using the latter functions to check if PHP string contains a value remember to use the identical operators
  • Not all methods are case-insensitive, ensure to use the strtolower() method

Источник

str_contains

Performs a case-sensitive check indicating if needle is contained in haystack .

Parameters

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

User Contributed Notes 7 notes

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 ;
>
>
?>

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 ?: «»`;

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

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];

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);
>

// Polyfill for PHP 4 — PHP 7, safe to utilize with PHP 8

if (! function_exists ( ‘str_contains’ )) function str_contains ( string $haystack , string $needle )
return empty( $needle ) || strpos ( $haystack , $needle ) !== false ;
>
>

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

Источник

Check if String Contains a Character in PHP

This tutorial will discuss about a unique way to check if string contains a character in php.

To check if a string contains a given character or not, we can use the strpos() function. It accepts a string as the first parameter and a substring as a second parameter. Then it returns the index position of the first occurrence of the given substring in the string, whereas, if the given substring does not exist in the string that it returns false.

Now to check if a String Contains a Character, we can pass the string as the first argument and character as a second argument in the strpos() function. If return value is not false, then it means the given character exists in the string.

We have created a separate function for this,

function stringContainsChar($str, $char)

It accept a string and character as an arguments, and returns true if the given character exists in the given string.

Frequently Asked:

Let’s see the complete example,

 $strValue = "Last Train"; $char = "s"; if (stringContainsChar($strValue, $char)) < echo "The string contains the character."; >else < echo "The string does not contain the character."; >?>
The string contains the character.

Summary

We learned how to check if a string contains a character in PHP.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Читайте также:  Реализация javascript на java
Оцените статью