Reputation: 159
I am trying to get specific information out of an input string into variables by using wildcards in a match pattern.
$input = "my name is John Smith and I live in Las Vegas";
$pattern = "my name is * and I live in *";
I understand preg_match will give me all wildcards with (\w+), so replacing * in the pattern with (\w+) gives me "John Smith" and "Las Vegas" but how would I go about giving a variable name in the pattern so I can do
$pattern = "my name is *name and I live in *city";
and get the result put into variables like so:
$name = "John Smith"
$city = "Las Vegas"
any help to find the corresponding preg_match pattern will be highly appreciated! Also I wonder if the * character is a wise choice. Maybe $ or % makes more sense.
Upvotes: 0
Views: 91
Reputation: 456
here it is ( in php ) :
<?php
$input = "my name is John Smith and I live in Las Vegas";
$pattern = "/my\sname\sis\s(?P<name>[a-zA-Z\s]+)\sand\sI\sLive\sin\s(?P<loc>[a-zA-Z\s]+)/si";
preg_match($pattern,$input,$res);
$name = $res["name"];
$loc = $res["loc"];
var_dump($res);
result : https://eval.in/498117
Upvotes: 1