正则表达式:将空格转换为字符串数组的单词

时间:2021-05-02 16:51:37

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

3 个解决方案

#1


2  

If I don't misunderstand you, simply:

如果我不误解你,只需:

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

This will create a string array out of your string.

这将从字符串中创建一个字符串数组。

explode() in PHP Manual

PHP手册中的explode()

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.

你尝试过的东西不起作用,因为它是Javascript。如果你澄清了你想要达到的目标,以及Javascript如何进入图片,我们可以进一步提供帮助。

#2


1  

Use the explode function instead.

请改用爆炸功能。

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

#3


1  

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

你为什么不能使用爆炸?它似乎完全符合你的要求。

#1


2  

If I don't misunderstand you, simply:

如果我不误解你,只需:

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

This will create a string array out of your string.

这将从字符串中创建一个字符串数组。

explode() in PHP Manual

PHP手册中的explode()

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.

你尝试过的东西不起作用,因为它是Javascript。如果你澄清了你想要达到的目标,以及Javascript如何进入图片,我们可以进一步提供帮助。

#2


1  

Use the explode function instead.

请改用爆炸功能。

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

#3


1  

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

你为什么不能使用爆炸?它似乎完全符合你的要求。