Jump to content

Best Way To Search Each Subtring In Array


refiking

Recommended Posts

I have a script that takes forever to run.  Is there any way I can optimize this?  I want to check to see if $desc contains any of the values in $desc_array.  If so, I just want to echo $dbtime.  Here's what I have right now:

$dbtime = date('m/d/y h:i A',strtotime(str_replace(',','',$datetime).$tadj));
$desc_array = array("maintenance", "theatre", "golfing", "fishing");
$i = 0;
	foreach ($desc_array as $desc_filter) {
	$pos = strpos($desc, $desc_filter);
		if($pos !== false){
		$i++;
		}
	}
	if($i > 0){ echo $dbtime.'<br>'; }

Link to comment
Share on other sites

I'm not sure it'll be any faster.  But you could try:

// $haystack contains text to search
// $terms is array of terms to search
$haystack = explode( ' ', $haystack );
$haystack = array_unique( $haystack );
$found = array_intersect( $haystack, $terms );
print_r( $found );

Link to comment
Share on other sites

What's this print:

<?php
$haystack = explode( ' ', $desc);
$haystack = array_unique( $haystack );
echo '$haystack<pre>' . print_r( $haystack, true ) . '</pre>';
echo '$desc_array<pre>'.print_r( $desc_array, true ).'</pre>';
	if(count(array_intersect($haystack, $desc_array)) > 0 ){ 
	echo $dbtime; 
	}
	else{
	echo 'nope<br>';
	}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.