|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-03-20 11:45 UTC] vovan-ve at yandex dot ru
Description:
------------
If we want to search first substrings from list, we should make multiple calls to strpos() for each substring. Using PCRE will slowdown performance. So, we need some new function like:
int strpos_array(string $haystack, array $needles, string &$found [, int $offset = 0 ])
which will accept array of substrings in $needle, search first position of them. If nothing found then returns FALSE. If found any substring then assign it to $found and return its position.
The function name is not important. Other functions for case-insensitive search and/or for reverse search (stripos_array, strrpos_array, strripos_array) also useful.
Extending function strpos() to accept array in $needle is not good due to &$found parameter.
Good example of using such function is writing parser of some data like SQL dump. Performance of the function should be higher then PCRE.
Test script:
---------------
$string = 'foo;bar::baz-qwe';
$search = array('-', ';', '::');
$pos = strpos_array($string, $search, $found, 5);
if ($pos === false) {
echo "Nothing found";
}
else {
echo "Found '$found' at $pos";
}
Expected result:
----------------
Found '::' at 7
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 18:00:01 2025 UTC |
I dont think we should add such functionality that already can be done with a few lines of php code already, combining strpos/stripos with a foreach and you should get your result: <?php function strpos_array_impl($case_sensitive, $haystack, Array $needle, &$found = NULL, $position = 0) { if(!sizeof($needle) || empty($haystack)) { return(false); } $strpos_function = ($case_sensitive ? 'strpos' : 'stripos'); foreach($needle as $temp) { if(($pos = $strpos_function($haystack, $temp, $found, $position) !== false) { return($pos); } } return(false); } function strpos_array($haystack, Array $needle, &$found = NULL, $position = 0) { return(strpos_array_impl(false, $haystack, $needle, $found, $position)); } function stripos_array($haystack, Array $needle, &$found = NULL, $position = 0) { return(strpos_array_impl(true, $haystack, $needle, $found, $position)); } ?> Dont take that code for granted, as i wrote it on my cell so it might be buggy, but should show what I mean