Input sanitation

Hello dear php-experts,

I am very new to php and I am standing for a bit of code that I cannot understand. The code is supposed to take a user’s search query and highlight it on the page if it is found. To me it seems as if this is like horrible coding, but I would love if someone could tell me in detail what is happening in each step. Thank you so much in advance.

// if the user searches a query
if(isset($http[‘query’]) && $http[‘query’] != “”) {

// first generate the string to be put in the second preg_replace

$replaceWith = “preg_replace(’#\b”. str_replace(’\’, ‘\\’, $http[‘query’]) ."\b#i’, ‘<span class=“queryHighlight”>\\0’,’\0’)";

// the string to be searched in has to be freed from tags first and within this raw text we search with the preg_replace aboth the query string and mark it with the class queryHighlight

$transfersStr = preg_replace(’#(>((?>(([^><]+|(?R))))*<))#se’,$replaceWith,’>’.$transfersStr.’<’);

// Finally we cut the ‘<’ and ‘>’ we added
$transfersStr = str_replace(’"’, ‘"’, substr($transfersStr, 1, -1));}

// and print this string
print $transfersStr;

Well, this is a tricky subject. First, it really depends on what you are displaying. If you are attempting to highlight all text in a PHP page that match a keyword, you do it with just a simple string-replace. You can make it spanned if needed or just make it italics or whatever is needed. This of course only works if you have access to the page’s contents as one variable. It is seldom a real-world solution. But, if the content of the page is in one variable and the keyword from the search is in another, you can do this with one replace like this:

$content = preg_replace("/\b([a-z]${keyword}[a-z])\b/i","$1",$content);

Note that this format will will just make them bold. Also, a keyword of “honey” would also flag “honeydew” on purpose.
To just do the exact keyword, use this one…
$content = preg_replace("/\w*?$keyword\w*/i", “$0”, $content);

The keyword should be checked to have no quotes in it. Hope that helps…

Sponsor our Newsletter | Privacy Policy | Terms of Service