Jump to content

[SOLVED] Script working, but is there a better way?


NevadaSam

Recommended Posts

 

With this script I get the desired results of: Search words used: A big fast red truck

 

But I was wondering if there is a better way.

 

$str is received from a search form. A lot of other code not shown here removes all words less than three characters, because they are not use in a mysql search. This script echos all the words the user submitted with the words that were actually used in bold. Could I have done this better?

 

<?php
$str = "A big fast red truck";
$searchwords = preg_replace( '#(\b[\w]{0,3}\b)#', '', $str ); // removes <=3 char words
$searchwords = preg_replace('/\s+/', ' ', $searchwords); // removes extra spaces
$searchwords = explode(' ', $searchwords);
array_walk($searchwords, create_function('&$v, $k', '$v = "/\\b$v\\b/i";'));
$str = preg_replace($searchwords, '<strong>\\0</strong>', $str);
echo "Search words used: " . $str;
?> 

 

Sam

;

Seems pretty solid to me, as long as it is working and working well, no need to change it.

 

The only part I wonder about is where you "Remove" the extra spaces and than you explode by the space...wouldn't you rather use the www.php.net/trim function to handle that part if you are just removing extra spaces at the beginning and end of the string?

 

Either way seems pretty solid.

frost110: In my full code, I do use trim() to remove end spaces. while the beginning does not seem to be a problem, a space on the end will really mess it up. And I remove any extra spaces that may be between words along with comma, quotes, etc. In this small code it did not work right without removing extra white space. I think that was because when I remove 3 letter words only the text was taken out leaving the extra space that was with it. The actual input will come by a user via an input box so anything could happen.

 

Lumio: That may be a much better code. Looks like it should wrap words with 4 or more letters. I was going the long way around doing it backwards. I will try that.

 

Thanks to everyone who look and read.

 

Sam

;

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.