P110
P110

Reputation: 192

Php regex custom variables in string

I'm trying to create a simple speech based command interface, using pre-defined commands. The specific part that I am having an issue with is when the program is trying to understand parameters passed with the command. I have some working code but it isn't ideal for what I'd like.

For example, I might have a command that checks the weather as follows:

In london united kingdom what is the weather

and the pattern to be recognised would be this:

In _ what is the weather

I'm already getting the commands with some relevance based mysql queries, that's not my problem, my problem is separating out the context of "London united kingdom" from the command.

I have got some working code at the moment but it isn't ideal:

//SPLIT CONTEXT FROM COMMAND
$query = "in london what is the weather";
$trigger = "in _ what is the weather";
$triggers = explode("_", $trigger);
foreach($triggers as $word){
    $query = str_replace($word, "'", $query);
}
$query = explode("'", $query);
array_shift($query);

This will mean that $query['0'] = "london". But it can only support one word at a time, is there a way to support more than one word, by somehow treating it as a variable or something along those lines?

tl;dr

Cheers

Upvotes: 0

Views: 344

Answers (1)

Laurel
Laurel

Reputation: 6173

You can replace the _ in your "pattern" with (.+?)

To capture the end of the string, you can use (.+). Your way works too, but it's less efficient. The + (and *) are greedy by default (? is added to make it non-greedy), so they will go right to the end (and backtrack if needed to make a match, which will never happen since it's the end of the regex).

Your PHP code might look something like this:

$re = "~in (.+?) what is the (.+)~i"; 
$str = "in london united kingdom what is the weather"; 

preg_match($re, $str, $matches);

The i modifier ensures that it's not case sensitive (it's unnecessary if your strings are already all lowercase, as you said). It will match:

IN RUSSIA WHAT IS THE WEATHER

Of course, the matching will be sensitive to misspellings. It will not match:

In london united kingdom what is the whether

While it will be difficult to recognize all misspelled permutations of a phrase, you can account for some common abbreviations like:

in (.+?) what.*?s the (.+)

That will match:

in paris, france whats the weather and in poland what's the weather and also some other variations. It's not terribly sophisticated, and will also match in my backyard what changes the weather.

Upvotes: 1

Related Questions