|
Posted by Sandman on 09/07/05 17:23
In article <dfmj8b$95j$1@gemini.csx.cam.ac.uk>,
"brendan" <brendan_NOSPAM_@srl.cam.ac.uk> wrote:
> my regular expression knowledge is admittedly amateurish ... I have spent an
> hour trying to get this to work without any great success, but am in the
> middle of a big project so I can't waste a day fiddling around to get it to
> work (although I might have to if someone here can't help).
>
> I thought I would throw it out to the group to see if anyone could solve the
> problem quick and easy.
>
> I need to break a search string into components to search against a
> database.
> We want to allow the user to specify database columns by using
>
> [column name][colon][search text]
>
> i.e.
> "author:Jane Smith institution:university of Cambridge year:1976"
>
> so basically we have to split the string at the beginning of any word that
> ends in a colon.
> I need then get an array with column_name=>column_value to construct a SQL
> query from.
>
> At the moment I'm just getting garbage or parse errors ... Can anyone help?
> Accolades for anyone that can. A pint of lager for anyone in Cambridge that
> can!
> cheers
> Brendan.
This is one way to do it:
#!/usr/bin/php
<?
$string = "author:Jane Smith institution:university of Cambridge year:1976";
$m = preg_split("/\s*(\w+):/", $string, -1,
PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
for ($i=0;$i<=count($m)-1;$i+=2){
$sql_query[] = $m[$i] . " = '" . $m[$i+1] . "'";
}
print "select * from database.table where " . join(" and ", $sql_query);
?>
The output:
select * from database.table where author = 'Jane Smith' and institution =
'university of Cambridge' and year = '1976'
--
Sandman[.net]
Navigation:
[Reply to this message]
|