Reputation: 3325
I want to sluggify a camel-cased string by breaking up the words by their capitals, like so:
<?php
$classname = "MyBigClass";
$classname_arr = preg_split('/(?=[A-Z])/', $classname);
$slug = strtolower(implode("-",$classname_arr)); // outputs "my-big-class"
?>
But I don't want it to break up acronyms:
<?php
$classname = "FAQList";
... // outputs "f-a-q-list", I want it to be "faq-list"
How do I accomplish this? I can't find any relavant SO question-answers.
Upvotes: 0
Views: 114
Reputation: 6953
although @Wee Zel's answer is allready accepted (and for good reason) I wanna give an extention, that also works for cases like MyFAQ
:
<?php
$classname = "MyFAQ";
$classname_arr = preg_split('/(?=[A-Z][^A-Z])|(?<![A-Z])(?=[A-Z])/', $classname);
$slug = strtolower(implode("-", array_filter($classname_arr))); // outputs "my-faq"
echo $slug;
I just combined my first try in comments (a negative lookbehind) with Wee Zel's lookahead.
EDIT:
here's with some test cases. only the last one might not be what we want.
<?php
$classnames = Array("MyFAQ", "myFAQ", "FAQList","myClassName", "youHaveAProblem", "MyClassNNName");
function splitCamelCase($classname) {
$classname_arr = preg_split('/(?=[A-Z][^A-Z])|(?<![A-Z])(?=[A-Z])/', $classname);
$slug = strtolower(implode("-", array_filter($classname_arr))); // outputs "my-faq"
return $slug;
}
foreach($classnames as $classname) {
echo splitCamelCase($classname)."<br>\n";
}
// output:
// my-faq
// my-faq
// faq-list
// my-class-name
// you-have-a-problem
// my-class-nn-name
Upvotes: 3
Reputation: 1324
this checks for the next letter not being uppercase
$classname_arr = preg_split('/(?=[A-Z][^A-Z])/', $classname);
$slug = strtolower(implode("-", array_filter($classname_arr))); // outputs "my-big-class"
echo $slug;
note: using array_filter() to remove empty elements
Upvotes: 3