Match part of string with part of other string

145 Views Asked by At

I working on a simple search function where I want to match a part of a string with part of another string.

Example: The search term is: fruitbag I want to match the product: fruit applebag

I want to create something so that the system matches:

  • fruitbag
  • fruit applebag

Or even "fruit" and "bag".

In summary; parts inside a string need to match with parts inside the search term. Is this possible?

    $products = array(
        'fruit applebag',
        'pinapple',
        'carrots',
        'bananas',
        'coconut oil',
        'cabbage',
    );

    if( ! empty( $_POST['search'] ) ) {

        $s = $_POST['search'];
        $results = array();
        foreach( $products as $index => $product ) {

            if( preg_match( '/' . $s . '.*/i', $product, $matched ) ) {
                $results[] = $matched[0];
            }
        }
        print_r($results); 
        // This only returns fruit applebag if the search term is something like "fruit ap"
    }
2

There are 2 best solutions below

2
n-dru On BEST ANSWER

Use something like this (split the searched word into two parts and look for a match thas has characters between those two parts):

$products = array(
        'fruit applebag',
        'pinapple',
        'carrots',
        'bananas',
        'coconut oil',
        'cabbage',
    );
$s = 'fruitbag';
$results = array();
foreach( $products as $index => $product ) {
    for($i=1;$i<strlen($s);$i++){
        if(preg_match( '/' . substr($s,0,$i) . '.*'.substr($s,$i+1).'/i', $product, $matched ) ) {
            $results[] = $matched[0];
        }
    }
}
print_r($results);

Output:

Array ( [0] => fruit applebag [1] => fruit applebag )
0
Eric Leibenguth On

It is possible, but could be very costly. As stated, your requirement is that any substring of the search term is potentially relevant. So take fruitbag and generate a list of all substrings:

f,r,u,i,t,b,a,g,fr,ru,ui,it,tb,ba,ag,fru,rui,uit,...,bag,...,fruit,...,fruitbag

But you probably don't want that any word with the letter a be a match. So a first approach could be to specify a minimum number of letters (e.g. 3), which will significantly limit the potential matches. But even then... Does it make sense to match fru, or rui?

A better approach would be to use a dictionary, to extract actual words or syllables from your search string. (In your case, extract fruit and bag from fruitbag).

You can find an English dictionary fairly easily.