Php переменная есть строка

stristr

Returns all of haystack starting from and including the first occurrence of needle to the end.

Parameters

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

If true , stristr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

needle and haystack are examined in a case-insensitive manner.

Return Values

Returns the matched substring. If needle is not found, returns false .

Changelog

Version Description
8.2.0 Case folding no longer depends on the locale set with setlocale() . Only ASCII case folding will be done. Non-ASCII bytes will be compared by their byte value.
8.0.0 Passing an int as needle is no longer supported.
7.3.0 Passing an int as needle has been deprecated.

Examples

Example #1 stristr() example

$email = ‘USER@EXAMPLE.com’ ;
echo stristr ( $email , ‘e’ ); // outputs ER@EXAMPLE.com
echo stristr ( $email , ‘e’ , true ); // outputs US
?>

Example #2 Testing if a string is found or not

$string = ‘Hello World!’ ;
if( stristr ( $string , ‘earth’ ) === FALSE ) echo ‘»earth» not found in string’ ;
>
// outputs: «earth» not found in string
?>

Example #3 Using a non «string» needle

Notes

Note: This function is binary-safe.

See Also

  • strstr() — Find the first occurrence of a string
  • strrchr() — Find the last occurrence of a character in a string
  • stripos() — Find the position of the first occurrence of a case-insensitive substring in a string
  • strpbrk() — Search a string for any of a set of characters
  • preg_match() — Perform a regular expression 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

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

Источник

is_string

Возвращает true , если value является строкой, и false в противном случае.

Примеры

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

$values = array( false , true , null , ‘abc’ , ’23’ , 23 , ‘23.5’ , 23.5 , » , ‘ ‘ , ‘0’ , 0 );
foreach ( $values as $value ) echo «is_string(» ;
var_export ( $value );
echo «) color: #007700″>;
echo var_dump ( is_string ( $value ));
>
?>

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

is_string(false) = bool(false) is_string(true) = bool(false) is_string(NULL) = bool(false) is_string('abc') = bool(true) is_string('23') = bool(true) is_string(23) = bool(false) is_string('23.5') = bool(true) is_string(23.5) = bool(false) is_string('') = bool(true) is_string(' ') = bool(true) is_string('0') = bool(true) is_string(0) = bool(false)

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

  • is_float() — Проверяет, является ли переменная числом с плавающей точкой
  • is_int() — Проверяет, является ли переменная целым числом
  • is_bool() — Проверяет, является ли переменная булевой
  • is_object() — Проверяет, является ли переменная объектом
  • is_array() — Определяет, является ли переменная массивом

User Contributed Notes 3 notes

Using is_string() on an object will always return false (even with __toString()).

class B public function __toString () return «Instances of B() can be treated as a strings!\n» ;
>
>

$b = new B ();
print( $b ); //Instances of B() can be treated as a strings!
print( is_string ( $b ) ? ‘true’ : ‘false’ ); //false
?>

As noted earlier, is_string() returns false on an object that has a __toString() method. Here is a simple way to do a check that will work:

// determine if the passed argument can be treated like a string.
function is_stringy ( $text ) return ( is_string ( $text ) || ( is_object ( $text ) && method_exists ( $text , ‘__toString’ ));
>

is_string() of an integer or float returns false, so it might be useful to include an is_numeric() when checking if a value is stringy:

function is_stringy ( $val ) return ( is_string ( $val ) || is_numeric ( $val )
|| ( is_object ( $val ) && method_exists ( $val , ‘__toString’ )));
>
?>

Test code (which should print «vector N OK» for each test vector):
foreach ([[ NULL , false ], [ false , false ], [ true , false ],
[ 0 , true ], [[], false ], [ 0.1 , true ], [ «x» , true ],
[ «» , true ], [new Exception ( «x» ), true ]] as $idx => $vector ) list ( $val , $expected ) = $vector ;
if ( is_stringy ( $val ) != $expected ) print ( «mismatch at $idx \n» );
var_dump ( $val );
> else print ( «vector $idx OK\n» );
>
>
?>

Источник

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.

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

Источник

Читайте также:  Python import as private
Оцените статью