1

Users writing an article have the option to write some tags, tags are written like this:

tag1, tag2, tag3

So tags are stored like: $tags = "tag1, tag2, tag3";

I want to make sure, every tag has a minimum of 3 characters, so i need to validate the tags.

I have tried this:

$tagsstring = explode(",", $tags);

$tagslength = array_map('strlen', $tagsstring);

if (min($tagslength) < 3) {
echo "Error... Each tag has to be at least 3 characters.";
}

It seems to work, sometimes... But of you write:

tag1, df

It wont give an error.

Any suggestions?

3 Answers 3

4
$tagsstring = explode(",", $tags);

$trimmedtags = array_map('trim', $tagsstring);
$tagslength = array_map('strlen', $trimmedtags);

if (min($tagslength) < 3) {
echo "Error... Each tag has to be at least 3 characters.";
}

use this version it trims your strings before calcutlating the length.

Sign up to request clarification or add additional context in comments.

Comments

3

The issue is that by exploding on a bare comma on input such as tag1, df you make the resulting array be ['tag1', ' df'] -- the second string actually has a length of 3.

The are two approaches to fix this that spring to mind:

  1. Simply array_map with trim before calculating the lengths:

    $tagsstring = explode(",", $tags);
    $tagsstring = array_map('trim', $tagsstring);
    $tagsstring = array_map('strlen', $tagsstring);
    
  2. Use a regular expression and preg_split to do the splitting:

    $tagsstring = preg_split("/\s*,\s*/", $tags);
    $tagsstring = array_map('strlen', $tagsstring);
    

See it in action.

Comments

1

If i understand you correctly you said you want make sure I want to make sure, every tag has a minimum of 3 characters

if you are only worried about alphabetical charters then its a different game that means

tab1 is valid

tab200 is valid

t299 not valid

ta444 not valid

If this what you want then you can use this

$tags = "tag1, tag2, ta11  ,tag3 , df ";
$tags = explode ( ",", $tags );

function checker($tag) {
    preg_match_all ( '/[a-zA-Z]/u', $tag, $matches );

    return count ( $matches [0] );
}
foreach ( $tags as $tag ) {
    if (checker ( $tag ) < 3) {
        echo "Error... Each tag ($tag) has to be at least 3 characters.\n";
    }
}

Output

Error... Each tag ( ta11  ) has to be at least 3 characters.
Error... Each tag ( df ) has to be at least 3 characters.

2 Comments

Thank you Baba, nice solution. Numeric characters is allowed though. But maybe it should not be, and then this solution is nice to have, thanks
+1 i like when people take their time to review and appreciate everyone who as made effort to help them ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.