user2798227
user2798227

Reputation: 853

How to remove plural words from a string in PHP?

I have a string of words which has some words like

"Cloud", "Clouds", "Application", "Applications", "Event", "Events"

and some words like

"Access"

which are singular but have "s" at the end. I want to remove the plural words but I can't write a code to remove s from the end as it will remove "s" from all the words. I searched on Internet and couldn't find anything relevant. Can anyone help me with best way of doing this?

EDIT: How do I use CakePHP in my program? I have never used it before so don't have experience on it. I have that String variable in a function. It says I need to install Cake PHP, Can anyone tell me how to use it in the function?

Thanks

Upvotes: 2

Views: 3157

Answers (2)

floriank
floriank

Reputation: 25698

Use the Inflector class that comes with CakePHP.

debug(Inflector::singularize('People')); // will show person

http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::singularize

static Inflector::singularize($plural)

Input: Apples, Oranges, People, Men

Output: Apple, Orange, Person, Man

Honestly I don't know how exactly it is working internally but its doing a pretty good job with english words and you can even configure it to deal with special cases.

You can configure exceptions to the rules by defining them using Inflector::rules():

Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables'));
Inflector::rules('plural', array(
    'rules' => array('/^(inflect)ors$/i' => '\1ables'),
    'uninflected' => array('dontinflectme'),
    'irregular' => array('red' => 'redlings')
));
Inflector::rules('transliteration', array('/å/' => 'aa'));

Upvotes: 6

Mark Baker
Mark Baker

Reputation: 212502

There's no easy way of doing this in English: consider Clouds => Cloud, Fortresses => Fortress, Ladies => Lady, Sheep => Sheep... and simply stripping an s off could lead to problems (e.g. Lady's)... you might want to consider using a Porter Stemmer or similar

Upvotes: 3

Related Questions