如何限制标签中的字数?

我正在从事的项目是在BuddyPress/Wordpress上运行的专业网络站点。我们添加到每个人的个人资料的功能之一是标签的文本区域,例如:专业兴趣和个人兴趣,并会提示用户将其标签的字数保留为1-3个字,并以逗号分隔(例如“山地自行车,葡萄酒,钩编”)。 但是,我们有一些愚蠢的用户认为该区域是用于撰写论文的,例如“我喜欢打扮我的猫,赤身裸体地向着Motley Crue唱片跳舞,同时在皮划艇上寻找旅行优惠,”而不只是写“猫,杂色克鲁,旅行”...... 尽管明确说明了什么是标签、什么不是标签,用户仍然一无所知。因此我们决定尝试限制用户的输入字数——是否有一种好的方法来检查用逗号分隔的字符串,然后显示一个弹出窗口或其他警告,说:“嘿,标签不能超过3个字!”? 我发现了一些允许字符数限制的javascript脚本,但是没有可以将输入分开并计算逗号之的字数。 提前谢谢!

Sure. Put the string into an array and then count how many occurences.

$interests = explode(",", $_POST['interests']);
$total = count($interests);

explode will separate the textarea string into an array. You can then count how many elements are in the array and slap heads as needed!

Use the .split() method in JS, like so:

var str = "My really long annoying tag, my tag, good tag, lol";
var tags = str.split(",");
for(var tag in tags) {
    if(tags[tag].split(" ").length > 3) {
       alert("HEY DUMMY, '" + tags[tag] + "' is too long!!");
    } 

}