Jump to content

[SOLVED] I need to search an array for a string


refiking

Recommended Posts

Still didn't work.  Also tried in array and that didn't work, either.

 

$results = "I am testing this right now";
$options = array("am", "yes", "check");
if (strstr($results, $options)) {
echo "Successful";
}

 

here is the other one:

 

[code]
$results = "I am testing this right now";
$options = array("am", "yes", "check");
if (in_array($results, $options)) {
echo "Successful";
}

So you want to check if it contains any of the words in the array?

 

Then like this perhaps:

$results = "I am testing this right now";
$options = array("am", "yes", "check");

$results = explode(' ', preg_replace('#[^a-z ]#', '', strtolower($results)));

if (count(array_intersect($results, $options))) {
echo 'Successful';
}

 

Or like this:

$results = "I am testing this right now";
$options = array("am", "yes", "check");

foreach ($options as $option) {
if (preg_match('#\b' . preg_quote($option, '#') . '\b#i', $results)) {
	echo 'Successful';
	break;
}
}

I managed to get the preg match to work.  But, now I am getting duplicates.  In my options array, I placed both the upper and lower case values.  Is this what is causing that problem?  for example...

 

$options = array("web", "Web", "website", "Website");

yes.  Dan wrote the preg_match as case insensitive so you do not need both in your array. It would be better for you to only have a single version in your array and the preg_match will check for web Web WEB weB etc.. but if that is not possible (ex: if this array is being generated) then remove the i modifier in the preg_match

 

 

 

if (preg_match('#\b' . preg_quote($option, '#') . '\b#', $results)) {

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.