Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 214
caustic Avatar asked Mar 11 '15 02:03

caustic


People also ask

How do you replace spaces with dashes?

Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.

How do you make a lowercase in PHP?

The strtolower() function converts a string to lowercase. Note: This function is binary-safe. Related functions: strtoupper() - converts a string to uppercase.

How do you capitalize text in PHP?

The ucfirst() function converts the first character of a string to uppercase. Related functions: lcfirst() - converts the first character of a string to lowercase. ucwords() - converts the first character of each word in a string to uppercase.


2 Answers

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))); ?> 
like image 177
Alexander O'Mara Avatar answered Sep 22 '22 14:09

Alexander O'Mara


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

like image 41
Nolwennig Avatar answered Sep 23 '22 14:09

Nolwennig