sobigsoscary
sobigsoscary

Reputation: 5

How to check for tags

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

Answers (4)

Cadoc
Cadoc

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

xzyfer
xzyfer

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

RobertPitt
RobertPitt

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

GolezTrol
GolezTrol

Reputation: 116100

Err. How not? Explode the string using ',' as a separator and check for each value in the resulting array if it is a valid tag.

Upvotes: 0

Related Questions