3

你能帮我用一个函数来替换字符串,如下所示:

该字符串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

原谅我糟糕的英语。我希望我的问题足够清楚。

4

2 回答 2

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

试试看

于 2012-06-21T17:13:07.123 回答
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.
于 2013-06-26T14:47:23.770 回答