替换字符串以匹配复数或单数

时间:2012-06-21 17:06:28

标签: php regex string

你可以帮我一个函数来替换字符串如下:

字符串the boo[k|ks] [is|are] on the table将根据参数输出the book is on the tablethe books are on the table

<?php
    $unformated_str = "the boo[k|ks] [is|are] on the table";
    $plural = true;

    echo formatstr($unformated_str, $plural);
?>

输出:

the books are on the table

原谅我可怜的英语。我希望我的问题足够清楚。

2 个答案:

答案 0 :(得分:5)

这是一个使用preg_replace_callback()的函数:

function formatstr( $unformatted_str, $plural) {
    return preg_replace_callback( '#\[([^\]]+)\]#i', function( $match) use ($plural) {
        $choices = explode( '|', $match[1]);
        return ( $plural) ? $choices[1] : $choices[0];
    }, $unformatted_str);
}

$unformated_str = "the boo[k|ks] [is|are] on the table";

echo formatstr($unformated_str, false); // the book is on the table
echo formatstr($unformated_str, true); // the books are on the table

Try it out

答案 1 :(得分:0)

function plural (str, num) {// https://gist.github.com/kjantzer/4957176
    var indx = num == 1 ? 1 : 0;
    str = str.replace(/\[num\]/, num);
    str = str.replace(/{(.[^}]*)}/g, function(wholematch,firstmatch){
        var values = firstmatch.split('|');
        return values[indx] || '';
    });
    return str;
}
plural('There {are|is} [num] book{s}.', 21); //"There are 21 books."
plural('There {are|is} [num] book{s}.', 1);  //"There is 1 book.