0

How is it possible to remove all spaces but have a hyphen between words, especially when there are spaces at the beginning or end of the string?

For example:

"   Cow jumped   over the moon    "

should be:

"Cow-jumped-over-the-moon"

I tried the below but I'm not sure how to get rid of the spaces without hyphens before and after the string.

$string_with_dashes = str_replace(' ','-',$string);
ggorlen
  • 44,755
  • 7
  • 76
  • 106
jules2x
  • 73
  • 8
  • 2
    Does this answer your question? [php Replacing multiple spaces with a single space](https://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space). `preg_replace("/\s+/", "-", trim($string))` – ggorlen Jan 04 '20 at 12:06
  • @ggorlen Thanks - it answers a part of the question - not exactly what I'm looking for. – jules2x Jan 04 '20 at 12:08
  • Did you try the code? Looks like this produces the same output you want to me, `trim` the head and tail and `preg_replace` with `/\s+/`. – ggorlen Jan 04 '20 at 12:11
  • 1
    So modify the code in the answer it to fit your needs. It does what you ask. – M. Eriksson Jan 04 '20 at 12:11
  • @MagnusEriksson I see... Perfect - thank you! – jules2x Jan 04 '20 at 12:15

1 Answers1

4

You could trim the $string first

$string = " Cow jumped over the moon ";
$string_with_dashes = str_replace(' ','-',trim($string));
echo $string_with_dashes;

If you want to reduce multiple spaces between the words you can match 1+ horizontal whitespaces \h+ the replace those with a hyphen.

$string_with_dashes = preg_replace("/\h+/", "-", trim($string));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Sounds good!!! But what if there are two or three spaces withing the string. e.g. 3 spaces between `over` and `the`? – jules2x Jan 04 '20 at 12:09
  • 1
    In that case you can explode the string like: $stringArray = explode(" ", $string); /// it'll became a string. $joinedString = join("-", $stringArray); And after that implement the solution above – Fabio William Conceição Jan 04 '20 at 12:17