0

Is it possible in PHP Regex to do partial matching so that if I have an array like:

$words = array("john", "steve", "amie", "kristy", "steven");

and I supply "jo" it would return "john" or if "eve" is supplied, it returns "steve"?

4
  • 1
    why regex? Why not strpos("john", "jo")? Commented Feb 10, 2012 at 8:19
  • because when a search term is supplied, it should return a best match. strpos requires I know the word to compare against Commented Feb 10, 2012 at 8:20
  • You just said the word to compare against was jo. So iterate over the array and see where strpos() doesn't return False. I fail to see the problem. Commented Feb 10, 2012 at 8:21
  • @TimPietzcker nevermind I'm retarded Commented Feb 10, 2012 at 8:23

3 Answers 3

1
$words = array("john","jogi", "steve", "amie", "kristy", "steven");
foreach ($words as $value) {
    if (preg_match("|jo|", $value)) {
        $arr[] = $value;
    }
}
var_dump($arr);

This will return you array with john and jogi

Sign up to request clarification or add additional context in comments.

4 Comments

it is working , tell me one thing for eve will return steve and steven na? or you want only first match answer would be returned..
did you see the codepad link? I used codepad to execute your php code and it returns "null" and several warnings
I am sorry @dukevin ,I don't know why its not working in codepad ,but I am bit confident it is working in php ,I have tested using netbeans and php.
I found some post based on warning just go through it stackoverflow.com/questions/8859363/…
1

If you only need to find a substring, either use strpos (for case-sensitive search) or stripos for case-insensitive search.

If you need regex, then you can specify wildcards at both ends: /.*jo.*/ which will force it to always match "dojo", "jo", "joe", "dojos", etc.

To search in an array for your pattern, look at preg_grep - this lets you pass in a regex (/.*jo.*/) as the first parameter, and an array as the second ($words), and returns any elements which match your regex.

4 Comments

That just makes processing the regular expression more expensive.
I don't think he's worried about efficiency, from the answer he's accepted
That doesn’t mean you should propose inefficient solutions.
Well I'm sorry for trying to offer advice. I'll know better next time.
0

You could iterate through your array and match your items using preg_match.
If you don't supply a ^ and $ it automatically does partial matching.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.