定义:
我在处理 PHP string Differences with Dynamic restrictions 时遇到了这种情况。它可能是更好地理解我想要的东西的引用。
问题:
假设我有一个 main 字符串:
"This is a {1} string with {2} placeholders"
还有一个次要:
"This is a very similar string with data for the placeholders"
问题:
如何为每个占位符获取一个名为 $v1
、$v2
、$vn
的变量,其值“非常相似”和“数据”分别是什么?正如您所看到的,我需要为每个占位符分配不在主字符串中的子字符串。
注释:
我正在使用 PHP。
最佳答案
您应该能够使用正则表达式执行以下操作:
$pattern="/This is a (.*) string with (.*) placeholders/";
$subject="This is a very similar string with data for the placeholders";
preg_match($pattern,$subject,$matches);
$v1=$matches[1];
$v2=$matches[2];
参见http://php.net/manual/en/function.preg-match.php有关 php 中正则表达式的更多信息。
关于php - 将子字符串与占位符匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147196/