Forum Moderators: coopster

Message Too Old, No Replies

Wildcard search with REGEX?

         

jkwilson78

3:13 pm on Jul 9, 2008 (gmt 0)

10+ Year Member



I know next to nothing about REGEX but I'm sure it is possible to do what I want.

I need to sort through data I have to return all results that match a certain URL pattern:

For instance:

sub.*.my.domain.com

I want to find all urls that match the pattern above where the "*" represents a part of the url that could have any value as long as the rest of the url matches the format above.

Hope that makes sense

eelixduppy

3:17 pm on Jul 9, 2008 (gmt 0)



Try something like this:

$pattern = "/sub\.([^.]+)\.my\.example\.com/i";
if(preg_match($pattern, $string, $matches)) {
echo '<pre>'; print_r($matches); echo '<pre>';
} else {
echo 'Could not match anything in the string';
}

For more information regarding regular expressions, more specifically their pattern syntax, refer to the php.net's documentation: [php.net...]

[edited by: eelixduppy at 3:23 pm (utc) on July 9, 2008]

Receptional Andy

3:21 pm on Jul 9, 2008 (gmt 0)



The preg_match_all [php.net] function can achieve what you're after. Something like the below:


// example string
$string='example example example example sub.widget.my.domain.com sub.example.my.domain.com example example sub.example2.my.domain.com';

// match one or more letters in the pattern
$pattern="/(sub\.[a-z]+\.my\.domain\.com)/i";

// find the matches
preg_match_all($pattern,$string,$matches);

// $matches[0] is an array containing the strings found - see manual entry for how $matches is formulated
print_r($matches[0]);


Added: too quick for me, eelixduppy :)

[edited by: Receptional_Andy at 3:23 pm (utc) on July 9, 2008]