使用 preg_match 获取模式中的通配符作为特定变量

get wildcards in pattern as specific variables with preg_match

我试图通过在匹配模式中使用通配符将输入字符串中的特定信息放入变量中。

$input   = "my name is John Smith and I live in Las Vegas";
$pattern = "my name is * and I live in *";

我明白 preg_match 会给我所有带 (\w+) 的通配符,所以用 (\w+) 替换模式中的 * 会给我 "John Smith" 和 "Las Vegas" 但是怎么会我打算在模式中给出一个变量名,这样我就可以做

$pattern = "my name is *name and I live in *city";

并将结果放入变量中,如下所示:

$name = "John Smith"
$city = "Las Vegas"

如果能帮助找到相应的 preg_match 模式,我们将不胜感激!另外我想知道 * 字符是否是一个明智的选择。也许 $ 或 % 更有意义。

这里是(在 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);

结果:https://eval.in/498117