Php find chars in string

strstr

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

Note:

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

Note:

If you only want to determine if a particular needle occurs within haystack , use the faster and less memory intensive function strpos() instead.

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 , strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Return Values

Returns the portion of string, or false if needle is not found.

Changelog

Version Description
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 strstr() example

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

$user = strstr ( $email , ‘@’ , true );
echo $user ; // prints name
?>

See Also

  • stristr() — Case-insensitive strstr
  • strrchr() — Find the last occurrence of a character in a string
  • strpos() — Find the position of the first occurrence of a 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 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

Читайте также:  Php google sitemap ping

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.

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

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

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

Источник

strpos

Ищет позицию первого вхождения подстроки needle в строку haystack .

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

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

Если needle не является строкой, он приводится к целому и трактуется как код символа.

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

Если этот параметр указан, то поиск будет начат с указанного количества символов с начала строки. В отличии от strrpos() и strripos() данный параметр не может быть отрицательным.

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

Возвращает позицию, в которой находится искомая строка, относительно начала строки haystack (независимо от смещения (offset). Также обратите внимание на то, что позиция строки отсчитывается от 0, а не от 1.

Возвращает FALSE , если искомая строка не найдена.

Эта функция может возвращать как boolean FALSE , так и не-boolean значение, которое приводится к FALSE . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Использование ===

$mystring = ‘abc’ ;
$findme = ‘a’ ;
$pos = strpos ( $mystring , $findme );

// Заметьте, что используется ===. Использование == не даст верного
// результата, так как ‘a’ находится в нулевой позиции.
if ( $pos === false ) echo «Строка ‘ $findme ‘ не найдена в строке ‘ $mystring ‘» ;
> else echo «Строка ‘ $findme ‘ найдена в строке ‘ $mystring ‘» ;
echo » в позиции $pos » ;
>
?>

Пример #2 Использование !==

$mystring = ‘abc’ ;
$findme = ‘a’ ;
$pos = strpos ( $mystring , $findme );

// Оператор !== также можно использовать. Использование != не даст верного
// результата, так как ‘a’ находится в нулевой позиции. Выражение (0 != false) приводится
// к false.
if ( $pos !== false ) echo «Строка ‘ $findme ‘ найдена в строке ‘ $mystring ‘» ;
echo » в позиции $pos » ;
> else echo «Строка ‘ $findme ‘ не найдена в строке ‘ $mystring ‘» ;
>
?>

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

// Можно искать символ, игнорируя символы до определенного смещения
$newstring = ‘abcdef abcdef’ ;
$pos = strpos ( $newstring , ‘a’ , 1 ); // $pos = 7, не 0
?>

Примечания

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

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

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

Источник

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