从可能带有逗号或空格的字符串中创建标签数组

问题描述 投票:0回答:1

我需要创建一个标签数组,以传递给tags_input函数内部的WordPress wp_insert_post()。这些标签是用户输入的。我要求用户用逗号分隔,但我知道有些用户不会这样做,只会写单词,因此,如果用户输入“ The Rolling Stones”,而另一个用户输入“ The,Rolling,Stones”,我如何确保我的数组将始终包含:

$wp_tags = array("the","rolling","stones");

我可以这样做吗?

$wp_tags = array( "'" . preg_replace("!\s+!","','",strtolower($_POST['user_tags'])). "'" );
arrays tags comma
1个回答
0
投票

我发现要执行我想将我的代码尝试和explode()结合起来的操作,就像这样:

$wp_tags = explode(",",(preg_replace("!\s+!",",",strtolower($_POST['user_tags']))));

// strtolower makes it all lowercase
// preg_replace replaces all single/multiple white spaces with a comma
// explode uses those commas to split all the words and enter them into the array
© www.soinside.com 2019 - 2024. All rights reserved.