3

次のように文字列を置き換える関数を教えてください:

文字列は引数に応じてorthe 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 に答える