Reputation: 5
I want to force the user to enter atleast one tag in tags field. However if they enter more than one, it has be seperated with commas, how would you check for this in php?
A tag in sense of 'php', 'arsenal', ermm... 'firefox' and not
'<html>' `'</html>'`.
In the same way that this question is tagged php, tags
Upvotes: 0
Views: 240
Reputation: 249
You can use a Regular Expression to do that.
An Example would be this one: ([a-zA-Z0-9]+)(([,][ ][a-zA-Z0-9]+))*
allowing all combinations of upper- and lowercase characters and numbers seperated by ,. Also it checks that two "tags" are sperated by a comma and a whitespace
Best check it at input level and only allow inputs that match above regex and again in the php backend by checking if the string you are about to handle is matching the regex and then explode it by the comma.
Upvotes: 0
Reputation: 14125
You could try explode as below. But it's pretty inflexible in that an unexpected space will alter the expected output.
$tagString = "my tag,your tag";
$tags = explode(',', $tagString);
if(count($tags) >= 1) {
echo "one tag or more";
} else {
echo "no tags"
}
I'd recommend using preg_split
, it's more forgiving.
$tagString = "my tag, your tag";
$tags = preg_split('/,\s?/', $tagString);
if(count($tags) >= 1) {
echo "one tag or more";
} else {
echo "no tags"
}
Upvotes: 1
Reputation: 57268
the simplest method would be to explode the string by the comma, for example:
explode(",",$tags);
this will be a list of tags
Upvotes: 0