开发者

How to search through POSTed form values using regex and return results

I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.

The members are stored in a SESSION variable:

$_SESSION['members'] = js开发者_开发知识库on_decode($jsonFile);

but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!

-Manoj


I think I'd be using a database to store the data rather than JSON so that you can use the LIKE searches, e.g.

SELECT * FROM users WHERE name LIKE 'Jon%'

If you absolutely have to use JSON you could loop through all members and use a regexp like

preg_match('/^'.$term.'.*/i', $element, $matches);

to check them all.


If the $jsonFile contents is an array of some sort, you may find preg_grep() of use, though it doesn't work on multidimensional arrays. You might have have to loop over each individual member record and grep the relevant fields yourself, something like:

foreach ($_SESSION['members'] as $idx => $member) {
     ... match relevant fields...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜