1

Possible Duplicate:
Add a prefix to each item of a PHP array

I try to use Boolean mode full text search.

If a user types more than two words, it supposes to make like this.

Search Keyword :   Apple Macbook Air 

Result :   +Apple +Macbook +Air

So, I made a php command to make this happen, but didn't work.

$ArrayKeywords = explode(" ", $b_keyword);
for($i = 0; $i < sizeof($ArrayKeywords); $i++)
$array_keyword = '+"$ArrayKeywords[$i]" ';

can you tell me how to make this happen?

Community
  • 1
  • 1
james
  • 225
  • 6
  • 20
  • Shouldn't it be like `$array_keyword = "+".$ArrayKeywords[$i];` – skos May 23 '12 at 07:12
  • @Sachyn your code doesn't work :( – james May 23 '12 at 07:13
  • "It didn't work" isn't good enough problem description, even though in this case it's obvious what the problem is. Try to describe what happens with the code you have (error message? invalid output? something else?) when you ask a question. – JJJ May 23 '12 at 07:15

5 Answers5

4

Can also do (demo)

echo preg_replace('(\w+)', '+$0', 'Apple Macbook Air');
Gordon
  • 312,688
  • 75
  • 539
  • 559
3

Why not just do this:

$keyword = '+' . trim(str_replace(' ',' +',$b_keyword));
Jamie Bicknell
  • 2,306
  • 17
  • 35
2

Don't really need to for loop there

// trims off consecutive spaces in the search term
$b_keyword = preg_replace('/\s+/', ' ', $b_keyword); 
$ArrayKeywords = explode(" ", $b_keyword);
echo '+' . implode(' +', $ArrayKeywords);
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
2

I see there's a bit of a misunderstanding how variables inside strings work.

You may have learned that anything inside single quotes is parsed as is and inside double quotes the variables' contents are printed, like so:

$foo = 'bar';

echo 'foo: $foo';    // result:  foo: $foo
echo "foo: $foo";    // result:  foo: bar

But, you can't combine the two methods; putting double quotes inside single quotes doesn't make the variable's contents printed. The double quotes work only if the entire string is delimited by them. Therefore the following won't work:

echo 'foo: "$foo"';  // result:  foo: "$foo"

Expanding this to your case, you can just replace the single quotes with double quotes and drop the inner double quotes.

$array_keyword .= "+$ArrayKeywords[$i] ";

Also note that you have to concatenate the new words into the variable (.=), otherwise the variable is overwritten on each loop.

Side note: it's much easier to use a foreach loop than a for loop when looping through arrays:

$ArrayKeywords = explode(" ", $b_keyword);
$array_keyword = '';
foreach( $ArrayKeywords as $keyword ) {
    $array_keyword .= '+$keyword ";
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
2

If you want it for tabs, newlines, spaces, etc.

echo preg_replace('(\s+)', '$0+', ' Apple Macbook Air');
//output: +Apple +Macbook +Air
Vishal
  • 2,161
  • 14
  • 25