I want to implement a small routine that generates the plural form of the name of an entity in Spanish. Basically, it takes a WordInCSharpCase or a wordInJavaCase, such as MedioDePago (payment method), and it appends an “s” at right before the first non-lowercase character (excluding the first character), which in this case would produce the string MediosDePago (payment methods). In C#, this routine was:
public string Pluralize(string input)
{
int i = 0;
while (++i < input.Length)
if (!char.IsLower(input[i]))
break;
StringBuilder builder = new StringBuilder(input);
builder.Insert(i, 's');
return builder.ToString();
}
Now I need to implement this routine in PHP, but I cannot find an equivalent of C#’s char.IsLower. The only thing I have found is ctype_lower, but it takes a string as an input, and creating/testing/discarding several strings would be too inefficient. Does PHP have a function that tests whether a single character is in lower case?
Well, first off, creating several strings is not inefficient. A string is a native type in PHP and it’s quite efficient at doing it. What I would do is something like this:
Or, as @Kevin suggests in the comments:
It’s more efficient since it doesn’t need to capture past the first non-lowercase character.