Php find if char is in string

strstr

Возвращает подстроку строки haystack , начиная с первого вхождения needle (и включая его) и до конца строки haystack .

Замечание:

Эта функция учитывает регистр символов. Для поиска без учёта регистра используйте stristr() .

Замечание:

Если нужно лишь определить, встречается ли подстрока needle в haystack , используйте более быструю и менее ресурсоёмкую функцию strpos() .

Список параметров

До PHP 8.0.0, если параметр needle не является строкой, он преобразуется в целое число и трактуется как код символа. Это поведение устарело с PHP 7.3.0, и полагаться на него крайне не рекомендуется. В зависимости от предполагаемого поведения, параметр needle должен быть либо явно приведён к строке, либо должен быть выполнен явный вызов chr() .

Если установлен в true , strstr() возвращает часть строки haystack до первого вхождения needle (исключая needle).

Возвращаемые значения

Возвращает часть строки или false , если needle не найдена.

Список изменений

Версия Описание
8.0.0 Передача целого числа ( int ) в needle больше не поддерживается.
7.3.0 Передача целого числа ( int ) в needle объявлена устаревшей.

Примеры

Пример #1 Пример использования strstr()

$email = ‘name@example.com’ ;
$domain = strstr ( $email , ‘@’ );
echo $domain ; // выводит @example.com

$user = strstr ( $email , ‘@’ , true );
echo $user ; // выводит name
?>

Смотрите также

  • stristr() — Регистронезависимый вариант функции strstr
  • strrchr() — Находит последнее вхождение символа в строке
  • strpos() — Возвращает позицию первого вхождения подстроки
  • strpbrk() — Ищет в строке любой символ из заданного набора
  • preg_match() — Выполняет проверку на соответствие регулярному выражению

User Contributed Notes 10 notes

strstr() is not a way to avoid type-checking with strpos().

If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).

findZero ( ‘01234’ ); // found a zero
findZero ( ‘43210’ ); // did not find a zero
findZero ( ‘0’ ); // did not find a zero
findZero ( ’00’ ); // found a zero
findZero ( ‘000’ ); // found a zero
findZero ( ’10’ ); // did not find a zero
findZero ( ‘100’ ); // found a zero

function findZero ( $numberString ) if ( strstr ( $numberString , ‘0’ )) echo ‘found a zero’ ;
> else echo ‘did not find a zero’ ;
>
>
?>

Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn’t be using it anyway.

Читайте также:  Php переменные html формы

There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn’t_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack.

My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using.

Been using this for years:

/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = ‘this/that/whatever’;
* $result = rstrstr($haystack, ‘/’)
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/

function rstrstr ( $haystack , $needle )
return substr ( $haystack , 0 , strpos ( $haystack , $needle ));
>
?>

You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )

function rstrstr ( $haystack , $needle , $start = 0 )
return substr ( $haystack , $start , strpos ( $haystack , $needle ));
>

If you want to emulate strstr’s new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.

For those in need of the last occurrence of a string:

function strrstr ( $h , $n , $before = false ) $rpos = strrpos ( $h , $n );
if( $rpos === false ) return false ;
if( $before == false ) return substr ( $h , $rpos );
else return substr ( $h , 0 , $rpos );
>
?>

For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

$haystack = ‘php-homepage-20071125.png’ ;
$needle = ‘-‘ ;
$result = substr ( $haystack , 0 , strpos ( $haystack , $needle )); // $result = php
?>

Lookout for logic inversion in old code!

In PHP 8, if the needle is an empty string, this function will return 0 (not false), implying the first character of the string matches the needle. Before PHP 8, it would return false when the needle is an empty string.

There other string functions that are affected by similar issues in PHP 8: strpos(), strrpos(), stripos(), strripos(), strchr(), strrchr(), stristr(), and this function, strstr()

If you are checking if the return value === false then you will be misled by this new behaviour. You also need to check if the needle was an empty string. Basically, something like this:

$result = $needle ? strstr ( $haystack , $needle ) : false ;
?>

PHP makes this easy for you. When working with domain portion of email addresses, simply pass the return of strstr() to substr() and start at 1:

Читайте также:  Apache пишет нет php

Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.

function strstr_after ( $haystack , $needle , $case_insensitive = false ) $strpos = ( $case_insensitive ) ? ‘stripos’ : ‘strpos’ ;
$pos = $strpos ( $haystack , $needle );
if ( is_int ( $pos )) return substr ( $haystack , $pos + strlen ( $needle ));
>
// Most likely false or null
return $pos ;
>

// Example
$email = ‘name@example.com’ ;
$domain = strstr_after ( $email , ‘@’ );
echo $domain ; // prints example.com
?>

When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding «��» to a string of size 10, you would get: «à&a» => the second character is cut.

This function will remove any unterminated HTML special characters from the string.

function cut_html ( $string )
<
$a = $string ;

while ( $a = strstr ( $a , ‘&’ ))
<
echo «‘» . $a . «‘\n» ;
$b = strstr ( $a , ‘;’ );
if (! $b )
<
echo «couper. \n» ;
$nb = strlen ( $a );
return substr ( $string , 0 , strlen ( $string )- $nb );
>
$a = substr ( $a , 1 , strlen ( $a )- 1 );
>
return $string ;
>
?>

Источник

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
Читайте также:  Post com curl php

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

Источник

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