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


You can actually use the StringHelper::toKebabCase function for this:

$string = 'Hello there';
$result = StringHelper::toKebabCase($string);
// => 'hello-there'
  • Can you give an example on how to call this function please? – Adam Menczykowski Jan 29 '16 at 11:10
  • Trying this: $urlslug = toKebabCase($member->membersCompanyName); results in: Call to undefined function Craft\toKebabCase() – Adam Menczykowski Jan 29 '16 at 11:14
  • 1
    @AdamMenczykowski Just updated the answer with an example. – Brandon Kelly Jan 29 '16 at 13:00
  • $string = StringHelper::toKebabCase('test this string'); does it! – Adam Menczykowski Jan 29 '16 at 13:00

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 Hello-there

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')));


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.