dukevin
dukevin

Reputation: 23178

RegEx Partial string matching

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

Upvotes: 0

Views: 2863

Answers (3)

Poonam
Poonam

Reputation: 4631

$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

Upvotes: 1

Marc-Christian Schulze
Marc-Christian Schulze

Reputation: 3254

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.

Upvotes: 0

Joe
Joe

Reputation: 15802

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.

Upvotes: 1

Related Questions