I want to convert a String into kebab-case.
'Hello there' -> 'hello-there'
I'm working in the Element API, so haven't got the pleasure of using the simple Twig filter. I guess there is a way of doing it in PHP. Any suggestions? Thank you
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.Sign up to join this community
You can actually use the StringHelper::toKebabCase function for this:
$string = 'Hello there'; $result = StringHelper::toKebabCase($string); // => 'hello-there'
I guess you could make use of some php functions to do this:
$string = 'Hello there';
First explode the string using a space as the seperator
$result = explode(" ", $string);
This will give you an array like
array(0 => 'Hello' 1 => 'there')
Then you can implode the array, using an
- as the "glue"
$result = implode('-', $result);
Which will then give you
Then use strtolower to make it lowercase
$result = strtolower($result);
To simplify this, you can just do it all at once
$result = strtolower(implode('-',explode(" ", 'Hello there')));