我正在寻找一个函数、类或函数集合来协助模式匹配字符串的过程,因为我有一个需要大量模式匹配的项目,并且我想要一些更易于阅读和维护的东西比原始 preg_replace (或正则表达式周期)。
我提供了一个伪示例,希望它能帮助您理解我的要求。
$subject = '$2,500 + $550 on-time bonus, paid 50% upfront ($1,250), 50% on delivery ($1,250 + on-time bonus).';
$pattern = '$n,nnn';
pattern_match($subject, $pattern, 0);
将返回“$2,500”。
$subject = '$2,500 + $550 on-time bonus, paid 50% upfront ($1,250), 50% on delivery ($1,250 + on-time bonus).';
$pattern = '$n,nnn';
pattern_match($subject, $pattern, 1);
将返回一个数组,其值为:[$2,500]、[$1,250]、[$1,250]
正如我正在尝试编写的那样,该函数使用“n”表示数字,“c”表示小写字母,“C”表示大写字母,其中任何非字母数字字符都代表其自身。
如有任何帮助,我们将不胜感激。
最佳答案
<?php
// $match_all = false: returns string with first match
// $match_all = true: returns array of strings with all matches
function pattern_match($subject, $pattern, $match_all = false)
{
$pattern = preg_quote($pattern, '|');
$ar_pattern_replaces = array(
'n' => '[0-9]',
'c' => '[a-z]',
'C' => '[A-Z]',
);
$pattern = strtr($pattern, $ar_pattern_replaces);
$pattern = "|".$pattern."|";
if ($match_all)
{
preg_match_all($pattern, $subject, $matches);
}
else
{
preg_match($pattern, $subject, $matches);
}
return $matches[0];
}
$subject = '$2,500 + $550 on-time bonus, paid 50% upfront ($1,250), 50% on delivery ($1,250 + on-time bonus).';
$pattern = '$n,nnn';
$result = pattern_match($subject, $pattern, 0);
var_dump($result);
$result = pattern_match($subject, $pattern, 1);
var_dump($result);
关于php - PHP 中的模式匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5504835/