以一种识别自定义if语句的方式解析纯文本

时间:2012-08-07 02:05:10

标签: php regex arrays

我有以下字符串:

$string = "The man has {NUM_DOGS} dogs."

我正在通过以下函数运行它来解析它:

function parse_text($string)
{
    global $num_dogs;

    $string = str_replace('{NUM_DOGS}', $num_dogs, $string);

    return $string;
}

parse_text($string);

其中$num_dogs是预设变量。根据{{​​1}},这可能会返回以下任何字符串:

  • 这个男人有一只狗。
  • 这个男人有两只狗。
  • 这个男人有500只狗。

问题是,在“男人有1只狗”的情况下, dog 是多元化的,这是不希望的。我知道这可以通过不使用$num_dogs函数来解决,而是执行类似的操作:

parse_text

但是在我的应用程序中,我解析的不仅仅是if($num_dogs = 1){ $string = "The man has 1 dog."; }else{ $string = "The man has $num_dogs dogs."; } 而且要编写所有条件需要很多行。

我需要一种速记方式,我可以写入初始{NUM_DOGS},我可以通过解析器运行,理想情况下,这不会限制我只有两种真/假的可能性。

例如,让

$string

是否清楚最后发生了什么?我试图使用方括号内的部分在垂直条之后开始创建数组,然后将新数组的键与{NUM_DOGS}的解析值进行比较(现在将是$ num_dogs变量)在竖线的左侧),并返回带有该键的数组条目的值。

如果这并不完全令人困惑,是否可以使用preg_ *函数?

4 个答案:

答案 0 :(得分:12)

您的问题的前提是,您希望匹配特定的模式,然后在执行其他处理后替换 < / strong>匹配的文字。

似乎是preg_replace_callback

的理想候选人

捕获匹配的括号,引号,括号等的正则表达式可能会变得相当复杂,而使用正则表达式完成所有操作实际上效率非常低。事实上,如果你需要,你需要编写一个合适的解析器。

对于这个问题,我将假设复杂程度有限,并使用正则表达式进行两阶段解析。


首先,我可以考虑使用最简单的正则表达式来捕捉大括号之间的标记。

/{([^}]+)}/

让我们打破它。

{        # A literal opening brace
(        # Begin capture
  [^}]+  # Everything that's not a closing brace (one or more times)
)        # End capture
}        # Literal closing brace

当应用于preg_match_all的字符串时,结果如下所示:

array (
  0 => array (
    0 => 'A string {TOK_ONE}',
    1 => ' with {TOK_TWO|0=>"no", 1=>"one", 2=>"two"}',
  ),
  1 => array (
    0 => 'TOK_ONE',
    1 => 'TOK_TWO|0=>"no", 1=>"one", 2=>"two"',
  ),
)

到目前为止看起来不错。

请注意,如果您的字符串中嵌套了大括号,即{TOK_TWO|0=>"hi {x} y"},则此正则表达式将无效。如果这不是问题,请跳到下一部分。

可以进行顶级匹配,但我能够做到的唯一方法是通过递归。大多数正则表达式的老手会告诉你,只要你将递归添加到正则表达式,它就会停止成为一个正则表达式。

这是额外的处理复杂性所在,而对于长而复杂的字符串,很容易耗尽堆栈空间并导致程序崩溃。如果您需要使用它,请仔细使用。

递归正则表达式taken from one of my other answers并进行了一些修改。

`/{((?:[^{}]*|(?R))*)}/`

分解。

{                   # literal brace
(                   # begin capture
    (?:             # don't create another capture set
        [^{}]*      # everything not a brace
        |(?R)       # OR recurse
    )*              # none or more times
)                   # end capture
}                   # literal brace

这次输出只匹配顶级大括号

array (
  0 => array (
    0 => '{TOK_ONE|0=>"a {nested} brace"}',
  ),
  1 => array (
    0 => 'TOK_ONE|0=>"a {nested} brace"',
  ),
)

同样,除非必须,否则不要使用递归正则表达式。 (如果系统有旧的PCRE库,您的系统可能甚至不支持它们)


如果令牌具有与之关联的选项,那么我们需要解决这个问题。根据您的问题,我建议不要让两个片段匹配,我建议按照我的示例使用令牌保留选项。 {TOKEN|0=>"option"}

让我们假设$match包含匹配的令牌,如果我们检查管道|,并取出其后的所有内容的子字符串,我们将留下您的选项列表,我们再次使用正则表达式解析它们。 (别担心我最后会把所有东西都放在一起)

/(\d)+\s*=>\s*"([^"]*)",?/

分解。

(\d)+    # Capture one or more decimal digits
\s*      # Any amount of whitespace (allows you to do 0    =>    "")
=>       # Literal pointy arrow
\s*      # Any amount of whitespace
"        # Literal quote
([^"]*)  # Capture anything that isn't a quote
"        # Literal quote
,?       # Maybe followed by a comma

示例匹配

array (
  0 => array (
    0 => '0=>"no",',
    1 => '1 => "one",',
    2 => '2=>"two"',
  ),
  1 => array (
    0 => '0',
    1 => '1',
    2 => '2',
  ),
  2 => array (
    0 => 'no',
    1 => 'one',
    2 => 'two',
  ),
)

如果你想在引号中使用引号,你必须为它制作自己的递归正则表达式。


总结一下,这是一个有效的例子。

一些初始化代码。

$options = array(
    'WERE' => 1,
    'TYPE' => 'cat',
    'PLURAL' => 1,
    'NAME' => 2
);

$string = 'There {WERE|0=>"was a",1=>"were"} ' .
    '{TYPE}{PLURAL|1=>"s"} named bob' . 
    '{NAME|1=>" and bib",2=>" and alice"}';

一切都在一起。

$string = preg_replace_callback('/{([^}]+)}/', function($match) use ($options) {
    $match = $match[1];

    if (false !== $pipe = strpos($match, '|')) {
        $tokens = substr($match, $pipe + 1);
        $match = substr($match, 0, $pipe);
    } else {
        $tokens = array();
    }

    if (isset($options[$match])) {
        if ($tokens) {
            preg_match_all('/(\d)+\s*=>\s*"([^"]*)",?/', $tokens, $tokens);

            $tokens = array_combine($tokens[1], $tokens[2]);

            return $tokens[$options[$match]];
        }
        return $options[$match];
    }
    return '';
}, $string);

请注意错误检查是最小的,如果您选择不存在的选项,将会出现意外结果。

可能有很多简单的方法来完成所有这些,但我只是接受了这个想法,然后继续使用它。

答案 1 :(得分:6)

首先,它有点值得商榷,但如果你能轻易避免它,只需将$num_dogs作为参数传递给函数,因为大多数人都认为全局变量是邪恶的!

接下来,为了获得“s”,我通常会这样做:

$dogs_plural = ($num_dogs == 1) ? '' : 's';

然后就这样做:

$your_string = "The man has $num_dogs dog$dogs_plural";

它与执行if / else块基本相同,但代码行数较少,您只需编写一次文本。

至于其他部分,我仍然对你要做的事情感到困惑,但我相信你正在寻找某种转换方式

{NUM_DOGS}|0=>"dogs",1=>"dog called fred",2=>"dogs called fred and harry",3=>"dogs called fred, harry and buster"]

成:

switch $num_dogs {
    case 0:
        return 'dogs';
        break;
    case 1:
        return 'dog called fred';
        break;
    case 2:
        return 'dogs called fred and harry';
        break;
    case 3:
        return 'dogs called fred, harry and buster';
        break;
}

最简单的方法是尝试使用explode()和正则表达式的组合,然后让它像我上面那样做。

答案 2 :(得分:6)

在紧要关头,我做了一些类似于你所要求的实现,模糊地类似于下面的代码。

这远不及@Mike的答案那么丰富,但它在过去已经成功了。

/**
 * This function pluralizes words, as appropriate.
 *
 * It is a completely naive, example-only implementation.
 * There are existing "inflector" implementations that do this
 * quite well for many/most *English* words.
 */
function pluralize($count, $word)
{
    if ($count === 1)
    {
        return $word;
    }
    return $word . 's';
}

/**
 * Matches template patterns in the following forms:
 *   {NAME}       - Replaces {NAME} with value from $values['NAME']
 *   {NAME:word}  - Replaces {NAME:word} with 'word', pluralized using the pluralize() function above.
 */
function parse($template, array $values)
{
    $callback = function ($matches) use ($values) {
        $number = $values[$matches['name']];
        if (array_key_exists('word', $matches)) {
            return pluralize($number, $matches['word']);
        }
        return $number;
    };

    $pattern = '/\{(?<name>.+?)(:(?<word>.+?))?\}/i';
    return preg_replace_callback($pattern, $callback, $template);
}

以下是一些类似于原始问题的例子......

echo parse(
    'The man has {NUM_DOGS} {NUM_DOGS:dog}.' . PHP_EOL,
    array('NUM_DOGS' => 2)
);

echo parse(
    'The man has {NUM_DOGS} {NUM_DOGS:dog}.' . PHP_EOL,
    array('NUM_DOGS' => 1)
);

输出结果为:

  该男子有两只狗。

     该男子有一只狗。

值得一提的是,在较大的项目中,我总是放弃任何自定义的滚动变化,转而支持GNU gettext,这似乎是多语言需要时最明智的方式。

答案 3 :(得分:0)

这是根据flussence在2009年发布的回复中复制的,以回复this question

您可能需要查看gettext extension。更具体地说,听起来ngettext()会做你想做的事情:只要你有一个可以计算的数字,它就会正确地复数词。

print ngettext('odor', 'odors', 1); // prints "odor"
print ngettext('odor', 'odors', 4); // prints "odors"
print ngettext('%d cat', '%d cats', 4); // prints "4 cats"

你也可以让它正确处理翻译的复数形式,这是它的主要目的,尽管还有很多额外的工作要做。