Php does string contain

Check if string contains a string in PHP

So how can I check $ip if it has the string of $x? Please do leave a comment if you are having a hard time understanding this situation. Thank you.

4 Answers 4

  • stristr() for a case insenstive version of this function.
  • strpos() Find the first occurrence of a string
  • stripos() Find the position of the first occurrence of a case-insensitive substring in a string

You can also use strpos() , and if you’re specifically looking for the beginning of the string (as in your example):

Or, if you just want to see if it is in the string (and don’t care about where in the string it is:

Or, if you want to compare the beginning n characters, use strncmp()

if (strncmp($ip, $x, strlen($x)) === 0) < // $ip's beginning characters match $x >

Use strstr()

$email = 'name@example.com'; $domain = strstr($email, '@'); echo $domain; // prints @example.com 

Based on $domain, we can determine whether string is found or not (if domain is null, string not found)

This function is case-sensitive. For case-insensitive searches, use stristr().

You could also use strpos().

$mystring = 'abc'; $findme = 'a'; $pos = strpos($mystring, $findme); // Note our use of ===. Simply == would not work as expected // because the position of 'a' was the 0th (first) character. if ($pos === false) < echo "The string '$findme' was not found in the string '$mystring'"; >else

Источник

Читайте также:  Android zip file java

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

Источник

PHP RFC: str_contains

str_contains checks if a string is contained in another string and returns a boolean value ( true / false ) whether or not the string was found.

The typical way to check if a string is contained in another is mostly done by using the functions strpos or strstr . Because this feature is such a common use-case in almost every project, it should deserve its own dedicated function: str_contains .

Repurposing strpos and strstr for this use-case has a few down sides. Either, they are:

Because of that, many PHP frameworks offer a helper function for this behavior, because it is so ubiquitous. This indicates the significance and the necessity pretty well.

Proposal

This RFC proposes the new basic function: str_contains

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

str_contains takes a $haystack and a $needle as arguments, checks if $needle is found in $haystack and returns a boolean value ( true / false ) whether or not the $needle was found.

The proposed function as code:

 str_contains("abc", "a"); // true str_contains("abc", "d"); // false // $needle is an empty string str_contains("abc", ""); // true str_contains("", ""); // true

Regarding empty string values as $needle:

As of PHP 8, behavior of “” in string search functions is well defined, and we consider “” to occur at every position in the string, including one past the end. As such, both of these will (or at least should) return true. The empty string is contained in every string. — Nikita Popov

Case-insensitivity and multibyte strings

In a recent discussion in the internals mailing list, we came to the conclusion, there is no need for a multibyte variant of this function (e.g. mb_str_contains ). The reason behind this is: A multibyte variant of this function would behave no different than the non-multibyte function. Multibyte variants behave differently when the offset/position has relevance at which the string was found. As this is not the case for this function, there is no need for that.

Concerning the case-insensitivity for this function: This might be a feature for the future, as the relevance for that is much less compared to the case-sensitive function. With that in mind, the only valid variants would be str_contains/mb_str_icontains. I assume PHP developers would be confused if this RFC offered such inconsistent variants of this function, so it’s better to start small and iterate upon that.

Backward Incompatible Changes

No backwards incompatible changes inside php itself.

There might be incompatibilities, if this function was implemented in the user-land code. But this issue would be noticed by the developer quickly as such global functions are added rather early in the application boot process. This is also the reason why this feature is proposed for PHP 8, as developers test their frameworks against new major versions more specifically.

Источник

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

Источник

How to check if a string contains a specific text [duplicate]

If you are checking the string if it has any text then this should work if(strlen($a) > 0) echo ‘text’; or if your concern is to check for specific word the follow the @Dai answer.

6 Answers 6

$haystack = "foo bar baz"; $needle = "bar"; if( strpos( $haystack, $needle ) !== false)
if( strpos( $a, 'some text' ) !== false ) echo 'text'; 

Note that my use of the !== operator (instead of != false or == true or even just if( strpos( . ) ) < ) is because of the "truthy"/"falsy" nature of PHP's handling of the return value of strpos .

As of PHP 8.0.0 you can now use str_contains

@Blender sorry, you’re right. I was thinking of the .NET String.IndexOf which returns -1 in event of a non-match. I’ve corrected my answer.

@PadronizaçãoSA The ! operator will affect the falsiness of the return value from strpos which means === won’t work the way it’s intended.

Empty strings are falsey, so you can just write:

Although if you’re asking if a particular substring exists in that string, you can use strpos() to do that:

if (strpos($a, 'some text') !== false)

http://php.net/manual/en/function.strpos.php I think you are wondiner if ‘some text’ exists in the string right?

if(strpos( $a , 'some text' ) !== false) 

If you need to know if a word exists in a string you can use this. As it is not clear from your question if you just want to know if the variable is a string or not. Where ‘word’ is the word you are searching in the string.

or use the is_string method. Whichs returns true or false on the given variable.

Источник

Оцените статью