2012-06-21 112 views
3

你可以帮我一个函数来替换字符串如下。替换字符串匹配单复数

<?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

那么究竟是什么问题? –

+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

+4

+1尼斯功能 –

+0

+1非常如此@DavidBélanger! – Havelock

+0

哇!尽我所需!谢谢! –

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.