alyx
alyx

Reputation: 2733

Regex: Words with spaces into string array

I have strings that I'm printing as:

$string = "winter coats gloves hats blankets sleeping bags tarps milk magnesia shoes boots art";

That I need to regex into a string array, like:

$newString = array ('winter','coats','gloves','hats','blankets','sleeping','bags','tarps','milk','magnesia','shoes','boots','art');

The challenge is, how to add only ' on each end, while ',' to replace the spaces...

So far I have this, which doesn't work...

$string = str.replace(/\s+/g, '','',$string);

Upvotes: 1

Views: 276

Answers (3)

Paul Sanwald
Paul Sanwald

Reputation: 11329

any reason you can't use explode for this? it would seem to do exactly what you want.

Upvotes: 1

kapa
kapa

Reputation: 78671

If I don't misunderstand you, simply:

$array = explode(' ', $string);

This will create a string array out of your string.

explode() in PHP Manual

What you have tried does not work because it is Javascript. If you clarify a bit what you're trying to achieve exactly, and how Javascript comes into the picture, we could help further.

Upvotes: 2

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

Use the explode function instead.

$array = explode (' ', $string);

Upvotes: 1

Related Questions