0

I writing a function to search within my database. I wanted to eliminate uneccessary white spaces between words so I used preg_split. I have not used preg split before so I used print_r to see if it did what I was hoping for it to do (elimminate white spaces). Yet when I used print_r I got nothing back on my screen to show the array after I typed words in the search.

function search_results($keywords){
    $returned_results = array();
    $where = "";

    $keywords = preg_split('/[\s]+/', $keywords);
    print_r($keywords);

}

I would greatly appreciate it if someone could give me an idea as to what I did wrong, or better tips.

Octavius
  • 583
  • 5
  • 19

3 Answers3

1

You don't get any matches with your regexp, that's why you don't get any array. Try this instead:

 $keywords = preg_split("/\\s/", $keywords);
Undrium
  • 2,558
  • 1
  • 16
  • 24
0

I tested out your function with search_results("hi there"); It ran perfectly here on my end, no issues. Here's the results I got as expected:

Array
(
    [0] => hi
    [1] => there
)
Ultimater
  • 4,647
  • 2
  • 29
  • 43
0

Tyr this

$base_str = "this    is a   string  with multiple    spaces between  some words.            "; 


$start = microtime(1); 
for ($i=0; $i<100000; $i++){ 
    $string = $base_str; 
    while(strpos($string, '  ') !== false) 
    { 
         $string = str_replace('  ', ' ', $string); 
    } 
} 

echo $string;
Codesen
  • 7,724
  • 5
  • 29
  • 31