Php strpos and array

strpos

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

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

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

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

Если этот параметр указан, то поиск будет начат с указанного количества символов с начала строки. Если задано отрицательное значение, отсчёт позиции начала поиска будет произведён с конца строки.

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

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

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

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

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

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

Примеры

Пример #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() — Возвращает позицию первого вхождения подстроки без учёта регистра
  • str_contains() — Определяет, содержит ли строка заданную подстроку
  • str_ends_with() — Проверяет, заканчивается ли строка заданной подстрокой
  • str_starts_with() — Проверяет, начинается ли строка с заданной подстроки
  • strrpos() — Возвращает позицию последнего вхождения подстроки в строке
  • strripos() — Возвращает позицию последнего вхождения подстроки без учёта регистра
  • strstr() — Находит первое вхождение подстроки
  • strpbrk() — Ищет в строке любой символ из заданного набора
  • substr() — Возвращает подстроку
  • preg_match() — Выполняет проверку на соответствие регулярному выражению
Читайте также:  Java lang noclassdeffounderror in windows

User Contributed Notes 38 notes

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use:

To know that a substring is present (in any position including 0), you can use either of:

!== FALSE (recommended)
> -1 (note: or greater than any negative number)

To know that a substring is at the start of the string, you must use:

To know that a substring is in any position other than the start, you can use any of:

> 0 (recommended)
!= 0 (note: but not !== 0 which also equates to FALSE)
!= FALSE (disrecommended as highly confusing)

Also note that you cannot compare a value of «» to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don’t distinguish between the substring’s presence versus position. With a strict equivalence operator (=== or !==) it will always return false.

This is a function I wrote to find all occurrences of a string, using strpos recursively.

function strpos_recursive ( $haystack , $needle , $offset = 0 , & $results = array()) <
$offset = strpos ( $haystack , $needle , $offset );
if( $offset === false ) return $results ;
> else $results [] = $offset ;
return strpos_recursive ( $haystack , $needle , ( $offset + 1 ), $results );
>
>
?>

This is how you use it:

$string = ‘This is some string’ ;
$search = ‘a’ ;
$found = strpos_recursive ( $string , $search );

if( $found ) foreach( $found as $pos ) echo ‘Found «‘ . $search . ‘» in string «‘ . $string . ‘» at position ‘ . $pos . ‘
‘ ;
>
> else echo ‘»‘ . $search . ‘» not found in «‘ . $string . ‘»‘ ;
>
?>

It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings.

# Works like expected. There is no accent
var_dump ( strpos ( «Fabio» , ‘b’ ));
#int(2)

# The «á» letter is occupying two positions
var_dump ( strpos ( «Fábio» , ‘b’ )) ;
#int(3)

# Now, encoding the string «Fábio» to utf8, we get some «unexpected» outputs. Every letter that is no in regular ASCII table, will use 4 positions(bytes). The starting point remains like before.
# We cant find the characted, because the haystack string is now encoded.
var_dump ( strpos ( utf8_encode ( «Fábio» ), ‘á’ ));
#bool(false)

# To get the expected result, we need to encode the needle too
var_dump ( strpos ( utf8_encode ( «Fábio» ), utf8_encode ( ‘á’ )));
#int(1)

Читайте также:  Python datetime парсинг даты

# And, like said before, «á» occupies 4 positions(bytes)
var_dump ( strpos ( utf8_encode ( «Fábio» ), ‘b’ ));
#int(5)

when you want to know how much of substring occurrences, you’ll use «substr_count».
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :

function strpos_r($haystack, $needle)
if(strlen($needle) > strlen($haystack))
trigger_error(sprintf(«%s: length of argument 2 must be

$seeks = array();
while($seek = strrpos($haystack, $needle))
array_push($seeks, $seek);
$haystack = substr($haystack, 0, $seek);
>
return $seeks;
>

it will return an array of all occurrences a the substring in the string

$test = «this is a test for testing a test function. blah blah»;
var_dump(strpos_r($test, «test»));

I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

is a different beast then:

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.

/**
* Find the position of the first occurrence of one or more substrings in a
* string.
*
* This function is simulair to function strpos() except that it allows to
* search for multiple needles at once.
*
* @param string $haystack The string to search in.
* @param mixed $needles Array containing needles or string containing
* needle.
* @param integer $offset If specified, search will start this number of
* characters counted from the beginning of the
* string.
* @param boolean $last If TRUE then the farthest position from the start
* of one of the needles is returned.
* If FALSE then the smallest position from start of
* one of the needles is returned.
**/
function mstrpos ( $haystack , $needles , $offset = 0 , $last = false )
if(! is_array ( $needles )) < $needles = array( $needles ); >
$found = false ;
foreach( $needles as $needle )
$position = strpos ( $haystack , (string) $needle , $offset );
if( $position === false ) < continue; >
$exp = $last ? ( $found === false || $position > $found ) :
( $found === false || $position < $found );
if( $exp ) < $found = $position ; >
>
return $found ;
>

/**
* Find the position of the first (partially) occurrence of a substring in a
* string.
*
* This function is simulair to function strpos() except that it wil return a
* position when the substring is partially located at the end of the string.
*
* @param string $haystack The string to search in.
* @param mixed $needle The needle to search for.
* @param integer $offset If specified, search will start this number of
* characters counted from the beginning of the
* string.
**/
function pstrpos ( $haystack , $needle , $offset = 0 )
$position = strpos ( $haystack , $needle , $offset );
if( $position !== false )

for( $i = strlen ( $needle ); $i > 0 ; $i —)
if( substr ( $needle , 0 , $i ) == substr ( $haystack , — $i ))
< return strlen ( $haystack ) - $i ; >
>
return false ;
>

/**
* Find the position of the first (partially) occurrence of one or more
* substrings in a string.
*
* This function is simulair to function strpos() except that it allows to
* search for multiple needles at once and it wil return a position when one of
* the substrings is partially located at the end of the string.
*
* @param string $haystack The string to search in.
* @param mixed $needles Array containing needles or string containing
* needle.
* @param integer $offset If specified, search will start this number of
* characters counted from the beginning of the
* string.
* @param boolean $last If TRUE then the farthest position from the start
* of one of the needles is returned.
* If FALSE then the smallest position from start of
* one of the needles is returned.
**/
function mpstrpos ( $haystack , $needles , $offset = 0 , $last = false )
if(! is_array ( $needles )) < $needles = array( $needles ); >
$found = false ;
foreach( $needles as $needle )
$position = pstrpos ( $haystack , (string) $needle , $offset );
if( $position === false ) < continue; >
$exp = $last ? ( $found === false || $position > $found ) :
( $found === false || $position < $found );
if( $exp ) < $found = $position ; >
>
return $found ;
>

Читайте также:  Opencv python extract channel

Источник

msng / strpos_array.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function strpos_array ( $ haystack , $ needles , $ offset = 0 )
if (is_array( $ needles ))
foreach ( $ needles as $ needle )
$ pos = strpos_array( $ haystack , $ needle );
if ( $ pos !== false )
return $ pos ;
>
>
return false ;
> else
return strpos( $ haystack , $ needles , $ offset );
>
>

function strpos_array($haystack, $needles) if ( is_array($needles) ) foreach ($needles as $str) if ( is_array($str) ) $pos = strpos_array($haystack, $str);
> else $pos = strpos($haystack, $str);
>
if ($pos !== FALSE) return $pos;
>
>
> else return strpos($haystack, $needles);
>
>

function strpos_array($haystack, $needles) if ( is_array($needles) ) foreach ($needles as $str) if ( is_array($str) ) $pos = strpos_array($haystack, $str);
> else $pos = strpos($haystack, $str);
>
if ($pos !== FALSE) return $pos;
>
>
> else return strpos($haystack, $needles);
>
>

There’s a bit of an issue here.

Since you have multiple needles, it is possible that the first needle is found, but a later needle is found earlier in the string. The above function does not cover that. The below edit will adjust for it.

However this means returning an array of found needles back. If you want only the position of the first occurrence, do as so:
$cursor = reset( strpos_array( . ) );

If you want all matches for all needles, leave the reset() call out.

function strpos_array($haystack, $needles, $offset = 0) < if (is_array($needles)) < foreach ($needles as $needle) < $found = []; $pos = strpos_array($haystack, $needle); if ($pos !== false) < $found[$needle]=$pos; >> if(!empty($found)) < return asort($found, SORT_NUMERIC); >else < return false; >> return strpos($haystack, $needles, $offset); > 

Источник

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