php - 将子字符串与占位符匹配

标签 php substring match

定义:
我在处理 PHP string Differences with Dynamic restrictions 时遇到了这种情况。它可能是更好地理解我想要的东西的引用。

问题:
假设我有一个 ma​​in 字符串:

"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/

相关文章:

javascript - 刷新带有 <script> 标签的 div

yum 安装 php55-php-cli 后找不到 php 命令

PHP_INT_SIZE 返回 4 但我的操作系统是 64 位

c - 更好地优化搜索字符串的方式

python简单路由器url匹配器,如何重新匹配第一个 "/"出现

python - 比较多个数据帧添加新列填充二进制值以进行匹配

php - CakePHP : Send email to multiple addresses

regex - Powershell 使用 Regex 在字符串中查找字符串

c - 如何从C中的字符数组中获取 "substring"

postgresql tsvector 部分文本匹配