Php функция проверки строки

str_contains

Выполняет проверку с учётом регистра, указывающую, содержится ли needle в haystack .

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

Подстрока для поиска в haystack .

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

Возвращает true , если needle содержится в haystack , false в противном случае.

Примеры

Пример #1 Пример использования пустой строки »

if ( str_contains ( ‘абв’ , » )) echo «Проверка существования пустой строки всегда возвращает true» ;
>
?>

Результат выполнения данного примера:

Проверка существования пустой строки всегда возвращает true

Пример #2 Демонстрация чувствительности к регистру

$string = ‘ленивая лиса перепрыгнула через забор’ ;

if ( str_contains ( $string , ‘ленивая’ )) echo «Строка ‘ленивая’ найдена в проверяемой строке\n» ;
>

if ( str_contains ( $string , ‘Ленивая’ )) echo ‘Строка «Ленивая» найдена в проверяемой строке’ ;
> else echo ‘»Ленивая» не найдена потому что регистр не совпадает’ ;
>

Результат выполнения данного примера:

Строка 'ленивая' найдена в проверяемой строке "Ленивая" не найдена потому что регистр не совпадает

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

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

  • str_ends_with() — Проверяет, заканчивается ли строка заданной подстрокой
  • str_starts_with() — Проверяет, начинается ли строка с заданной подстроки
  • stripos() — Возвращает позицию первого вхождения подстроки без учёта регистра
  • strrpos() — Возвращает позицию последнего вхождения подстроки в строке
  • strripos() — Возвращает позицию последнего вхождения подстроки без учёта регистра
  • strstr() — Находит первое вхождение подстроки
  • strpbrk() — Ищет в строке любой символ из заданного набора
  • substr() — Возвращает подстроку
  • preg_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.

Читайте также:  Php com dotnet so

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

Источник

stristr

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

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

Строка, в которой производится поиск

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

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

needle и haystack обрабатываются без учёта регистра.

Читайте также:  Стили таблицы html примеры

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

Возвращает указанную подстроку. Если подстрока needle не найдена, возвращается false .

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

Версия Описание
8.2.0 Преобразование регистра больше не зависит от локали, установленной с помощью функции setlocale() . Будут преобразованы только символы ASCII. Байты не ASCII-кодировке будут сравниваться по значению байта.
8.0.0 Передача целого числа ( int ) в needle больше не поддерживается.
7.3.0 Передача целого числа ( int ) в needle объявлена устаревшей.

Примеры

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

$email = ‘USER@EXAMPLE.com’ ;
echo stristr ( $email , ‘e’ ); // выводит ER@EXAMPLE.com
echo stristr ( $email , ‘e’ , true ); // выводит US
?>

Пример #2 Проверка на вхождение строки

$string = ‘Hello World!’ ;
if( stristr ( $string , ‘earth’ ) === FALSE ) echo ‘»earth» не найдена в строке’ ;
>
// выводит: «earth» не найдена в строке
?>

Пример #3 Использование не строки в поиске

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

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

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

User Contributed Notes 8 notes

There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.

The following will generate a warning message in 4.0.6 and 4.2.3:
stristr(«haystack», «»);
OR
$needle = «»; stristr(«haystack», $needle);

This will _not_ generate an «Empty Delimiter» warning message in
4.0.6, but _will_ in 4.2.3:
unset($needle); stristr(«haystack», $needle);

Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.

Got round this by casting the value to a string.

if( ! stristr ( $file , (string) $myCustomer -> getCustomerID () ) ) <
// Permission denied
>
?>

An example for the stristr() function:

$a = «I like php» ;
if ( stristr ( » $a » , «LikE PhP» )) print ( «According to \$a, you like PHP.» );
>
?>

It will look in $a for «like php» (NOT case sensetive. though, strstr() is case-sensetive).

For the ones of you who uses linux.. It is similiar to the «grep» command.
Actually.. «grep -i».

function stristr_reverse ( $haystack , $needle ) <
$pos = stripos ( $haystack , $needle ) + strlen ( $needle );
return substr ( $haystack , 0 , $pos );
>
$email = ‘USER@EXAMPLE.com’ ;
echo stristr_reverse ( $email , ‘er’ );
// outputs USER

Читайте также:  Html дизайн с кнопками

I think there is a bug in php 5.3 in stristr with uppercase Ä containing other character

if you search only with täry it works, but as soon as the word is tärylä it does not. TÄRYL works fine

function aim ( $page ) if( stristr ( $_SERVER [ ‘REQUEST_URI’ ], $page )) return ‘ ‘ ;
>
>
?>

usage:

handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.

$i = implode ( » » , $argv ); //implode all the settings sent via clie
$e = explode ( «-» , $i ); // no lets explode it using our defined seperator ‘-‘

//now lets parse the array and return the parameter name and its setting
// since the input is being sent by the user via the command line
//we will use stristr since we don’t care about case sensitivity and
//will convert them as needed later.

while (list( $index , $value ) = each ( $e ))

//lets grap the parameter name first using a double reverse string
// to get the begining of the string in the array then reverse it again
// to set it back. we will also «trim» off the » default»>$param = rtrim ( strrev ( stristr ( strrev ( $value ), ‘=’ )), » keyword»>);

//now lets get what the parameter is set to.
// again «trimming» off the = sign

$setting = ltrim ( stristr ( $value , ‘=’ ), » keyword»>);

// now do something with our results.
// let’s just echo them out so we can see that everything is working

echo «Array index is » . $index . » and value is » . $value . «\r\n» ;
echo «Parameter is » . $param . » and is set to » . $setting . «\r\n\r\n» ;

?>

when run from the CLI this script returns the following.

[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=three

Array index is 0 and value is a.php
Parameter is and is set to

Array index is 1 and value is val1=one
Parameter is val1 and is set to one

Array index is 2 and value is val2=two
Parameter is val2 and is set to two

Array index is 3 and value is val3=three
Parameter is val3 and is set to three

Источник

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