School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 300,495 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,849 people online right now. Registration is fast and FREE... Join Now!




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 - 04: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.
Go to the top of the page
+Quote Post


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: 11/8/09 04:51AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month