php - PHP 中的模式匹配函数

标签 php pattern-matching

我正在寻找一个函数、类或函数集合来协助模式匹配字符串的过程,因为我有一个需要大量模式匹配的项目,并且我想要一些更易于阅读和维护的东西比原始 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/

相关文章:

php - 在 PhpStorm 中关闭自动完成

php - 从一个选项卡导航到另一个选项卡

php - 用 PHP 正则表达式替换单词或单词组合

php - 图像分类 - 检测平面图

scala - 用匹配器计数

python - 正则表达式用于嵌入其余匹配中的多字符串?

Python - 单行与多行正则表达式

PHP、HTML、Javascript执行顺序

php - 在 symfony 应用程序中首次登录时强制更改密码

java - MD5 Java模式