Jump to content

Archived

This topic is now archived and is closed to further replies.

dagnasty

PHP function to find string within a string from array of strings

Recommended Posts

I've seen it before, I just cannot remember the function.

say I have an array of words:

cat
dog
fish
bucket
cheese
wheel

and am looking in a bigger string to see if any of them exist (not case sensitive) within a string:

"the monkey jumped from the bucket"

What was that function name? Thanks.

Share this post


Link to post
Share on other sites
I can't think of [i]just one[/i] function that does this, I know a handfull exist for replacements, but not searches, well, none come to mind. YOu could do it like this though:
[code]<?php
$words = array("cat","dog","fish","bucket","cheese","wheel");
$str = "the monkey jumped from the bucket";
$found = array();
foreach($words as $w) {
    if(stripos($str,$w) !== FALSE) $found[] = $w;
}
?>[/code]

Share this post


Link to post
Share on other sites
undefined function stripos(); :(

My guess is that this function is only for PHP 5?

Do I have an alternative function to use?

Share this post


Link to post
Share on other sites
stripos is a PHP5 only function, you must be using PHP4 or lower. So you'll have to use strpos

Share this post


Link to post
Share on other sites
Alternatively, if you convert the sentence to an array of words

[code]<?php
$words = array ('cat','dog','fish','bucket','cheese','wheel');
$words2 = explode(' ', strtolower("the monkey jumped from the bucket"));
$found = array_intersect($words, $words2);

// view results
echo '<pre>', print_r($found, true), '</pre>';
?>
[/code]

Share this post


Link to post
Share on other sites
[quote author=Barand link=topic=101778.msg403339#msg403339 date=1153852857]
Alternatively, if you convert the sentence to an array of words

[code]<?php
$words = array ('cat','dog','fish','bucket','cheese','wheel');
$words2 = explode(' ', strtolower("the monkey jumped from the bucket"));
$found = array_intersect($words, $words2);

// view results
echo '<pre>', print_r($found, true), '</pre>';
?>
[/code]
[/quote]Yeah, that was one of the other ways I was thinking too. If you go about it this way you'll have to strip out any punctuation if it's present in your actual data though...

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.