你可以帮我一个函数来替换字符串如下:
字符串the boo[k|ks] [is|are] on the table
将根据参数输出the book is on the table
或the 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
原谅我可怜的英语。我希望我的问题足够清楚。
答案 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
答案 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.