Forum Moderators: coopster

Message Too Old, No Replies

stristr: check for several possibilities?

         

encyclo

3:49 am on Dec 31, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm using
stristr
for a really simple check of a string to see if it contains the text "foo". I think I'm missing something obvious, but how can I check to see whether a string contains either "foo", "bar" or "baz"? I tried pipes but that doesn't seem to work. Can I use
stristr
or is there another function I've overlooked?

Thanks for your help!

keno

4:16 am on Dec 31, 2005 (gmt 0)

10+ Year Member



Have you looked at the examples below?

I'm a C guy - somebody pointed this out to me before...

[us2.php.net...]

Edit Add:
Sorry, I think I answered the wrong question. I didn't read your headline.

In C you could look for the string in three seperate lines using if/else.

encyclo

6:58 pm on Dec 31, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks keno, I have it set up already as three different
stristr
blocks with if, else if, else if, but it seems just so overcomplicated - I was hoping that there was a function which could just check the string once and look for one of three (or more) possibilities. Something like
foo¦bar¦baz
.

coopster

8:12 pm on Jan 1, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I'd go with a preg_match() [php.net]. Also, I have noticed lately with PHP5 that regular expressions are often outperforming some of the string functions that the PHP documentation say are faster.

<added>
I just realized you were using stristr() and I was thinking stripos(). stripos() is a PHP5 function, that is why I commented on the performance. Still, a preg_match is going to work well here for you.
</added>

<pre> 
<?php
$strings = array(
'this string',
"this\nstring\n",
"thisfoostring",
"this\nbaz\nstring",
"this foo bar baz string",
"this bazstring"
);
foreach ($strings as $string) {
if (preg_match_all("/foo¦bar¦baz/is", $string, $matches)) {
print htmlentities($string) . "\n";
print_r($matches);
print "\n\n";
}
}
?>
</pre>