Jump to content

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


dagnasty

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.
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]
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 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...

Archived

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

×
×
  • Create New...

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.