Felix
Felix

Reputation: 128

PHP parse sentence and store information in variables

In PHP I'm trying to make a natural text recognition system that can recognise what you write in an intelligent way.
I'd like it to match a sentence with a 'pattern' and store some information, for example if schedule a {scheduletype} with {person} at {time} is compared to Schedule a meeting with Ann at 3pm, the PHP code will create variables $scheduletype with the value meeting, $person with Ann and $time with 3pm. Is it also possible to make it work if the sentence is written in a different order, for example 'At 3pm shedule a meeting with Ann`?
I've tried looking on Google and Stack Exchange for this but unfortunately haven't found anything.

Here's my current code:

$pattern = 'schedule a ([a-zA-Z0-9\-\.\/\?_=&;]*) with ([a-zA-Z0-9\-\.\/\?_=&;]*) at ([a-zA-Z0-9\-\.\/\?_=&;]*)';
$content = 'shedule a meeting with Ann at 3pm';


$match = preg_match($pattern, strtolower($content) , $found);
print_r($match);

The problem is that my code doesn't assign anything to $preg_match.

Upvotes: 1

Views: 207

Answers (1)

delboy1978uk
delboy1978uk

Reputation: 12365

You can use this sort of named capture group regex:

#Schedule a (?<scheduletype>\w+)\swith\s(?<person>\w+)\sat\s(?<time>\w+)#

Example:

<?php

$regex= '#Schedule a (?<scheduletype>\w+)\swith\s(?<person>\w+)\sat\s(?<time>\w+)#';
preg_match($regex, 'Schedule a meeting with Ann at 3pm', $matches);

echo $matches['scheduletype']."\n";
echo $matches['person']."\n";
echo $matches['time']."\n";

Play with the regex here: https://regex101.com/r/6QPRsG/1/

Play with the code here: https://3v4l.org/OBOnY

Upvotes: 1

Related Questions