views:

283

answers:

2

I need a very specific function in PHP. Basically, I have two strings as arguments, one of which is a pattern that contains wildcards of variable length (*), and one of which is a string that matches that pattern. I need to get an array of the strings from the latter string that fill in the wildcards in the pattern.

For example:

  • Argument 1: "This is * string that I *"
  • Argument 2: "This is my awesome string that I created myself"
  • Return: array("my awesome","created myself")

What's the cleanest way to do this? Bear in mind that these are not always strings of english words as in the example, they could be any random characters.

+1  A: 

Sounds like homework. Here is a walk-through without any actual code:

Tokenize the pattern into strings and wildcards. Iterate over the tokens; each time the target string starts with a regular (string, non-wildcard) token, trim that string off. Each time you encounter a wild card token, find the index of the next token in the string and trim off up to that index. Store that. If at any time there is no match, return false. If you encounter the end of the string before the pattern is complete, return false. If the final token is a wildcard, save the remainder of the string.

Jeff Ober
Should work. I'll give it a go. It's not homework - perhaps just laziness.
Travis
+1  A: 

You could just replace the wildcards with a regex equivalent, and run it through preg_match.

Because it really does sound like homework, I won't give any specific code either, but I'd make good use of preg_replace (to replace the wildcards with regex equivalents) and preg_match (to build the array of matching substrings).

Phil Hayward
This seemed to me like the best way to do it, but if my pattern is an unknown string with these wildcards in it, is there any good way to escape that string so that regex treats each character as literal and not as part of the pattern? Like for instance if I have a "." or "[" in that pattern string, they'd have to stay the literal characters.
Travis
Never mind, preg_quote() is exactly what I was looking for. Thanks for your help.
Travis