Welcome to Dream.In.Code
Getting Help is Easy!

Join 98,767 Programmers for FREE!. Ask your question and get quick answers from Dream.In.Code experts. There are 1,048 online right now! We're the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a Expert

Register to Make This Box Go Away!


Finding mix variables types in another variable

 
Reply to this topicStart new topic

> Finding mix variables types in another variable

Pilot-Doofy
Group Icon



post 21 Oct, 2006 - 05:24 PM
Post #1


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.


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 7/20/08 03:36PM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month
-->