开发者

Can the inverse of this function be computed using regular expressions?

开发者 https://www.devze.com 2023-02-16 22:31 出处:网络
I have a function that converts a class name (in Spanish!) from singular form to plural form: function pluralize($element) {

I have a function that converts a class name (in Spanish!) from singular form to plural form:

function pluralize($element) {
    return preg_replace('/^([A-Za-z][a-z]*)([A-Z]|$)/', '\1s\2', $element);
}

Now I would like to define the inverse of this function. Is the fol开发者_运维问答lowing function valid?

function singularize($plural) {
    return preg_replace('/^([A-Za-z][a-z]*)(s)([A-Z]|$)/', '\1\3', $element);
}


It should work fine, but you don't need parentheses around the s in the second pattern. You also need to keep in mind that if you have multiple s, neither pattern is going to care about that. So the first pattern will change ClassX to ClasssX and the second will change it back to ClassX. Just something to keep in mind.


As a rule, only if 's' is excluded from the [a-z]* position
when creating the class name.

That would mean [a-z]* needs to exclude 's'. Like [a-rt-z]*
Then these might work.

/^([A-Za-z][a-rt-z]*) ([A-Z]|$)/x
/^([A-Za-z][a-rt-z]*)(s)([A-Z]|$)/x

edit - otherwise (with what you have), you would have to keep track of what state each classname is in. ie: if it hasn't been pluralized, it can't be singularized, otherwise an extra 's' might be stripped from the original class name.

The regex's above don't need to maintain state, but they are limited in form.
It might be better to add a distinguishing character into the class to differentiate it from singular/plural state. Maybe an underscore if its supported. Otherwise there will be no control or other identifiable marking to tell which is which.

0

精彩评论

暂无评论...
验证码 换一张
取 消