Page 1 of 1

Finding mix variables types in another variable Rate Topic: -----

#1 Pilot-Doofy  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 11
  • Joined: 09-October 06

Posted 21 October 2006 - 05:24 PM

If you've been around PHP for any amount of time I'm sure you're familiar with the predefined functions strstr() and stristr().

Well, you've probably also seen and/or used a few calls to the str_replace() function. As you probably realize, the str_replace() function has a MIXED variable type for all the argument of the function, yet it's still called str_replace().

: MIXED variable types means you can pass different variable types
: to the function and it still work, such as strings, arrays, etc.

So why can't strstr() and stristr() take mixed variable types? I was scratching my head and asking myself the same question. Well, wait no longer, here is a version of strstr() and stristr() combined which can also accept arrays OR strings are either argument. Here's the function:

function strFind($haystack, $needle, $case='i') {

$haystack = ( is_array($haystack) ) ? implode('', $haystack) : $haystack;

$func = ( $case == 'i' ) ? 'stristr' : 'strstr';

if ( is_array($needle) ) {
foreach($needle as $item) {
if ( $func($haystack, $item) ) {
return true;
} else {
if ( $func($haystack, $needle) ) {
return true;

return false; // Didn't find a match

} // End strFind()

Let me show you how to use it. Let's define our haystack and needle first.

$haystack = 'Hey guys!';
$needle = array('h', 'b', 'k');
$result = strFind($haystack, $needle);

In this case, the function would return true. Since by default the function searches with the case-insensitive method, it would match "h" and "H". However, this would return false:

$result = strFind($haystack, $needle, 's');

That tells it to search case-sensitively. While the actual value of the 3rd parameter doesn't matter (as long as it's not "i"), I just use "s" to make it clear what's going on.

Well, I hope you liked it.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1