David Garcia
David Garcia

Reputation: 2696

PHP: Skip word if character count < 3

I am using the following code to pull some keywords and add them as tags in wordpress.

if (!is_array($keywords)) {

    $count = 0;

    $keywords = explode(',', $keywords);

}

foreach($keywords as $thetag) {

    $count++;

    wp_add_post_tags($post_id, $thetag);

    if ($count > 3) break;

}

The code will fetch only 4 keywords, However on top of that, I want to pull ONLY if they are higher than 2 characters, so i dont get tags with 2 letters only.

Can someone help me.

Upvotes: 0

Views: 201

Answers (2)

valentinas
valentinas

Reputation: 4337

strlen($string) will give you the lenght of the string:

if (!is_array($keywords)) {
    $count = 0;
    $keywords = explode(',', $keywords);
}

foreach($keywords as $thetag) {
   $thetag = trim($thetag); // just so if the tags were "abc, de, fgh" then de won't be selected as a valid tag
   if(strlen($thetag) > 2){
      $count++;
      wp_add_post_tags($post_id, $thetag);
   }

   if ($count > 3) break;
}

Upvotes: 1

sachleen
sachleen

Reputation: 31131

Use strlen to check the length.

int strlen ( string $string )

Returns the length of the given string.

if(strlen($thetag) > 2) {
    $count++;
    wp_add_post_tags($post_id, $thetag);
}

Upvotes: 1

Related Questions