caustic
caustic

Reputation: 585

Convert spaces to dash and lowercase with PHP

I've tried a few long methods but I think I'm doing something wrong.

Here is my code

<?php print strtolower($blob); ?>

Which makes $blob lowercase, but additionally I need any spaces in $blob to be removed and replaced by a dash (-).

I tried this, but it didn't work

<?php print (str_replace(' ', '-', $string)strtolower($blob)); ?>

Can I accomplish this all in the one line?

Upvotes: 31

Views: 52515

Answers (3)

Iggy
Iggy

Reputation: 2121

BTW, In WordPress you can use sanitize_title_with_dashes

https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/

Upvotes: 4

Nolwennig
Nolwennig

Reputation: 1684

For a string wrap you can use the dedicated wordwrap function.

str_replace

str_replace online documentation

<?php

$str = 'Convert spaces to dash and LowerCase with PHP';

echo str_replace(' ', '-', strtolower($str));
// return: convert-spaces-to-dash-and-lowercase-with-php

wordwrap

wordwrap online documentation

$str = 'Convert spaces to dash and LowerCase with PHP';

echo wordwrap(strtolower($str), 1, '-', 0);
// return: convert-spaces-to-dash-and-lowercase-with-php

online code: https://3v4l.org/keWGr

Upvotes: 5

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

Yes, simply pass the return value of strtolower($blob) as the third argument of str_replace (where you have $string).

<?php print (str_replace(' ', '-', strtolower($blob))); ?>

Upvotes: 78

Related Questions