允许用户插入两列数据集的更好方法是什么?



我想要一种高效的方式,允许我的网站用户将歌曲列表上传到他们的个人资料页面。目前,我正在表单中使用需要特定格式的<textarea>。歌曲列表的格式必须如下:

Some Band Name,Name of the song
Some other Band,Name of that song
...etc

我的网站查找逗号,然后告诉网站每一行,逗号之前的是艺术家的名字,逗号之后的是歌曲的名字。不过,对于像这样的歌曲来说,这是一个问题

Neil Diamond,Girl, You'll be a Woman Soon

歌曲标题中的第二个逗号破坏了网站的逻辑,而他们的个人资料中实际插入的内容是:

Neil Diamond, "Girl"

有什么更好的方法可以让我的用户在他们的个人资料中添加歌曲列表(有时是数百首(?

编辑:为了更清晰,我正在寻找一种方法,让我网站上的前端登录用户能够通过HTML表单提交一组两列的日期。然后,这些数据将通过表单提交到我的Wordpress后端,并将每一行项目添加为Wordpress中的自定义帖子。我已经弄清楚了所有的后端逻辑,但我正在努力找到一种更好的方法来允许用户添加这些数据,而不仅仅是使用<textarea>输入框并希望他们的所有数据都符合所需的格式条件。

您可以使用两个textarea,一个是艺术家,另一个是歌曲
您可以使用另一个分隔符(歌曲标题不太常见的是|而不是,(。

您还可以使用Javascript进行更"动态"的操作,以便在用户单击"加号"按钮时再添加两个输入。您将得到POST数据作为两个数组:

<form id="form" method="post" action="https://postman-echo.com/post">
<div>
<input name="songs[name][]" value="Girld, You'll be a Woman soon">
<input name="songs[artist][]" value="Neil Diamond">
</div>
</form>
<button onclick="addMore()">Add one more song</button>
<button onclick="submit()">Submit form</button>
<script>
/**
* Add one more song inputs
*/
function addMore() {
// Create a div
const div = document.createElement("div");
// Create the name input
const name = document.createElement("input");
name.setAttribute("type", "text");
name.setAttribute("name", "songs[name][]");
name.setAttribute("placeholder", "Name");
// Create the artist input
const artist = document.createElement("input");
artist.setAttribute("type", "text");
artist.setAttribute("name", "songs[artist][]");
artist.setAttribute("placeholder", "Artist");
// Add the inputs to the div
div.appendChild(name);
div.appendChild(artist);
// Append the div to the form
document.getElementById("form").appendChild(div);
}
/**
* Submit the form
*/
function submit() {
document.getElementById("form").submit();
}
</script>

您应该在PHP中使用explode((方法,并使用第三个参数$limit:

如果limit设置为正,则返回的数组将最多包含个limit元素,最后一个元素包含字符串的其余部分。

因此,在您的情况下,如果您使用explode(',', 'Neil Diamond,Girl, You'll be a Woman Soon', 2),它将输出:

array(2) {
[0]=>
string(10) "Neil Diamond"
[1]=>
string(17) "Girl, You'll be a Woman Soon"
}

最新更新