?php How would I implement “preg_replace” into my simple search engine?
Here is what I have so far….
if (@$_POST['search']=="search")
{
@$keywords=split(" ",$_POST['keyword']);
foreach ($keywords As $keyword){
$keyword = get_magic_quotes_gpc() ? addslashes(trim($keyword)) : trim($keyword);
$search[]="itemname LIKE ‘%$keyword%’ OR message1 LIKE ‘%$keyword%’";
}
$search = join("OR ", $search);
$result=mysql_query("SELECT * FROM listed WHERE($search)");
while ($results = mysql_fetch_array($result))
{
$price=$results['price'];
$idno=$results['id'];
$title=$results['itemname'];
$description = $results['message1'];
$position=40;
$post = substr($description, 0, $position);
echo //the rest of the code won’t fit but this is where I echo my results…which works fine.
My search query is having a problem with searches containing symbols, such as ?,."!@#$%^&* I was wondering how I can filter these out using the preg_replace function.
My PHP is very minimal, so over-explaining your answers is greatly appreciated.
One Response
dt01pqt_pt
22 Sep 2009





Are you accepting my previous answer then?
This is the regular expression you would use /[#!@$%^&*]/
1. The forward slashes (/ /) means enclosed is a regular expression used in preg functions (perl syntax). That is a string used to match a string based on certain rules.
2. The braces mean ([ ]) what is enclosed is the optional literal characters to be matched. By optional it means that any of those characters should be matched where ever it occurs.
3. !@#$%^&* are the characters you want to match. The braces make them literal.
An example:
$str1 = "Th*is @string !cont$ains ba%d char^acte&rs";
echo preg_replace("/[#!@$%^&*]/", "", $str1); // This string contains bad characters
For a good tutorial on regular expressions:
http://weblogtoolscollection.com/regex/regex.php
Ereg is the PHP standard regular expression matching
http://uk.php.net/manual/en/ref.regex.php
Preg uses perl compatible syntax and is sometime a bit faster
http://uk.php.net/manual/en/ref.pcre.php
To check your regular expressions for ereg and preg matches
http://www.quanetic.com/regex.php
It takes a bit of a while to get used to regular expressions, but once you get the hang of it, it can be really powerful.
Hope that helps,
Paul