2012-06-21 142 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.