你能帮我用一个函数来替换字符串吗?
字符串 the boo[k|ks] [is|are] on the table
将输出 the book is on the table
或 the books are on表
根据参数。
<?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
请原谅我糟糕的英语。我希望我的问题足够清楚。
最佳答案
这是一个使用 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
关于php - 替换字符串以匹配复数或单数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143194/