Php strpos with array

искать массив php для частичного совпадения строк

существует ли какая-либо предопределенная функция, такая как in_array(), которая выполняет задание , а не выполняет цикл через и сравнивает все значения?

Как вы можете видеть из всех ответов, есть много способов сделать это. Попытайтесь приложить усилия к поиску в Google, прежде чем задавать следующий вопрос 🙂

12 ответов

Для частичного соответствия вы можете перебирать массив и использовать функцию поиска строк, например strpos().

function array_search_partial($arr, $keyword) < foreach($arr as $index =>$string) < if (strpos($string, $keyword) !== FALSE) return $index; >> 

Для точного соответствия используйте in_array()

Существует несколько способов.

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red'); 

Поиск массива с циклом:

$results = array(); foreach ($arr as $value) < if (strpos($value, 'green') !== false) < $results[] = $value; >> if( empty($results) ) < echo 'No matches found.'; >else

Использовать array_filter():

$results = array_filter($arr, function($value) < return strpos($value, 'green') !== false; >); 

Чтобы использовать Closures с другими аргументами, существует use -keyword. Таким образом, вы можете абстрагировать его и вложить в функцию:

function find_string_in_array ($arr, $string) < return array_filter($arr, function($value) use ($string) < return strpos($value, $string) !== false; >); > $results = find_string_in_array ($arr, 'green'); if( empty($results) ) < echo 'No matches found.'; >else

для поиска с таким же значением, как sql с «% иглой%», вы можете попробовать

$input = preg_quote('gree', '~'); // don't forget to quote input string! $data = array( 1 => 'orange', 2 => 'green string', 3 => 'green', 4 => 'red', 5 => 'black' ); $result = preg_filter('~' . $input . '~', null, $data); 

Вы можете использовать функцию array_search php. Он поддерживается в PHP >= 4.0.5.

$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red'); $m_array = preg_grep('/^green\s.*/', $array); 

$m_array содержит согласованные элементы массива.

array_search() не будет работать, потому что, как и in_array() он ищет только точное совпадение, а не подстроку.

array_walk($arr, function($item, $key) < if(strpos($item, 'green') !== false) < echo 'Found in: ' . $item . ', with key: ' . $key; >>); 
function check($string) < foreach($arr as $a) < if(strpos($a,$string) !== false) < return true; >> return false; > 

Это функция для обычных или многомерных массивов.

  • Дело в чувствительном
  • Работает для обычных массивов и многомерных изображений
  • Работает при нахождении полных или частичных укусов

Здесь код (версия 1):

function array_find($needle, array $haystack, $column = null) < if(is_array($haystack[0]) === true) < // check for multidimentional array foreach (array_column($haystack, $column) as $key =>$value) < if (strpos(strtolower($value), strtolower($needle)) !== false) < return $key; >> > else < foreach ($haystack as $key =>$value) < // for normal array if (strpos(strtolower($value), strtolower($needle)) !== false) < return $key; >> > return false; > 
$multiArray = array( 0 => array( 'name' => 'kevin', 'hobbies' => 'Football / Cricket'), 1 => array( 'name' => 'tom', 'hobbies' => 'tennis'), 2 => array( 'name' => 'alex', 'hobbies' => 'Golf, Softball') ); $singleArray = array( 0 => 'Tennis', 1 => 'Cricket', ); echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1 echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0 

Только для многомерных массивов — $column относится к имени ключа внутри каждого массива. Если $игла появилась более одного раза, я предлагаю добавить к ней, чтобы добавить каждый ключ в массив.

Вот пример, если вы ожидаете нескольких совпадений (версия 2):

function array_find($needle, array $haystack, $column = null) < $keyArray = array(); if(is_array($haystack[0]) === true) < // for multidimentional array foreach (array_column($haystack, $column) as $key =>$value) < if (strpos(strtolower($value), strtolower($needle)) !== false) < $keyArray[] = $key; >> > else < foreach ($haystack as $key =>$value) < // for normal array if (strpos(strtolower($value), strtolower($needle)) !== false) < $keyArray[] = $key; >> > if(empty($keyArray)) < return false; >if(count($keyArray) == 1) < return $keyArray[0]; >else < return $keyArray; >> 

Возвращает ключ, если он имеет только одно совпадение, но если в любом столбце $есть несколько совпадений для $-ий, то он вернет массив соответствующих ключей.

Читайте также:  Java inputstream read all text

Источник

strpos

Find the numeric position of the first occurrence of needle in the haystack string.

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 specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

Return Values

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns false if the needle was not found.

This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

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.
7.1.0 Support for negative offset s has been added.

Examples

Example #1 Using ===

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

// Note our use of ===. Simply == would not work as expected
// because the position of ‘a’ was the 0th (first) character.
if ( $pos === false ) echo «The string ‘ $findme ‘ was not found in the string ‘ $mystring ‘» ;
> else echo «The string ‘ $findme ‘ was found in the string ‘ $mystring ‘» ;
echo » and exists at position $pos » ;
>
?>

Example #2 Using !==

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

// The !== operator can also be used. Using != would not work as expected
// because the position of ‘a’ is 0. The statement (0 != false) evaluates
// to false.
if ( $pos !== false ) echo «The string ‘ $findme ‘ was found in the string ‘ $mystring ‘» ;
echo » and exists at position $pos » ;
> else echo «The string ‘ $findme ‘ was not found in the string ‘ $mystring ‘» ;
>
?>

Example #3 Using an offset

// We can search for the character, ignoring anything before the offset
$newstring = ‘abcdef abcdef’ ;
$pos = strpos ( $newstring , ‘a’ , 1 ); // $pos = 7, not 0
?>

Notes

Note: This function is binary-safe.

See Also

  • stripos() — Find the position of the first occurrence of a case-insensitive substring in a string
  • str_contains() — Determine if a string contains a given substring
  • str_ends_with() — Checks if a string ends with a given substring
  • str_starts_with() — Checks if a string starts with a given substring
  • 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
Читайте также:  Css width 100vw minus scrollbar

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.

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)

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

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 . ‘»‘ ;
>
?>

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

Источник

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