Skip to content

Instantly share code, notes, and snippets.

@msng
Last active June 28, 2022 20:15
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save msng/5039773 to your computer and use it in GitHub Desktop.
Save msng/5039773 to your computer and use it in GitHub Desktop.
PHP: strpos_array is strpos that can take an array as needle
<?php
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);
}
}
@sufimalek
Copy link

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

@carlos-silveira
Copy link

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

Thanks man!

@SuitespaceDev
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment