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"?

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
dukevin
  • 22,384
  • 36
  • 82
  • 111

3 Answers3

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.

Joe
  • 15,669
  • 4
  • 48
  • 83
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

Poonam
  • 4,591
  • 1
  • 15
  • 20
  • 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.. – Poonam Feb 10 '12 at 09:52
  • did you see the codepad link? I used codepad to execute your php code and it returns "null" and several warnings – dukevin Feb 10 '12 at 09:58
  • 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. – Poonam Feb 10 '12 at 10:05
  • I found some post based on warning just go through it http://stackoverflow.com/questions/8859363/warning-preg-match-internal-pcre-fullinfo – Poonam Feb 10 '12 at 10:09
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.

Marc-Christian Schulze
  • 3,154
  • 3
  • 35
  • 45