Replace string to match plural or singular
php, regex, string
Solution
Here is a function that uses `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
Problem
can you help me with a function to replace string as following: The string `the boo[k|ks] [is|are] on the table` will output `the book is on the table` or `the books are on the table` according to an argument. ``` <?php $unformated_str = "the boo[k|ks] [is|are] on the table"; $plural = true; echo formatstr($unformated_str, $plural); ?> ``` Output: ``` the books are on the table ``` Forgive my poor english. I hope I made my question clear enough.