18.01.2010

PHP Snippet: building plurals

I recently coded a handy little PHP function to return a grammatically correct sentence building its plurals depending on a passed numerical parameter and different flexions of the word separated by slashes. If you need other HTML tags than breaks inside the strings you will have to alter it, but other than that it supports <br />s.
See the example to get a picture:

<?PHP

getPlurals("There is/are still one/two/three/four slot/slots open.", 3);
// returns: There are still three slots open.

getPlurals("There is/are still one/two/three/four slot/slots open.", 1);
// returns: There is still one slot open.

getPlurals("There is/are still one/two/three/four slot/slots open.", 2);
// returns: There are still two slots open.

?>


or, to be more abstract:

<?PHP

getPlurals("I/You/She am/are/is hungry!", 1);
// returns: I am hungry!

getPlurals("I/You/She am/are/is hungry!", 2);
// returns: You are hungry!

getPlurals("I/You/She am/are/is hungry!", 3);
// returns: She is hungry!

?>

You can download the PHP file here or copy and paste it:

<?PHP

	function getPlurals($str, $nr)
	{

		$plurals_words = explode(' ', str_replace('<br/>','*_*',$str));
		foreach($plurals_words as &$word)
			if(strpos($word, '/'))
			{
				$word = explode('/', $word);
				$word = (count($word) < $nr ? array_pop($word) : $word[$nr-1]);
			}
		return str_replace('*_*','<br/>', implode(' ',$plurals_words));

	}
?>

Dan Borufka

...you might also be interested in:

1 comment

  1. February 17, 2010

    Wow, nice. I’ve tried to do things like this before but its always been really messy. Thanks!

Leave a Reply