简体   繁体   中英

Regular expression for tags in PHP using compound words

Here is my code so far:

if (preg_match('/\s/',$tagName)){
    $_ErrorMessage = "<div class='alert alert-danger' id='errorBox'>";
    $_ErrorMessage.= "<b>Error!</b> La etiqueta no puede contener espacios. Asegúrese de escribirla correctamente.";
    $_ErrorMessage.= "</div>";
} elseif(preg_match('/[^A-Z]/i', $tagName)){
    $_ErrorMessage = "<div class='alert alert-danger' id='errorBox'>";
    $_ErrorMessage.= "<b>Error!</b> La etiqueta no puede contener carácteres especiales. Cáracteres especiales son todos aquellos que no estan dentro del alfabeto. Por favor escríbala de nuevo.";
    $_ErrorMessage.= "</div>";
} else {
    $insertNewTagQuery = sprintf("INSERT IGNORE INTO solution_tags (SOLUTION_TAGS_NAME)VALUES(LOWER('%s'))", $tagName);
    if($DBConnect->query($insertNewTagQuery)){
        header("Location:http://127.0.0.1/helpdesk/admin/thankyou.php");
    }
}

With the code above, I'm checking whether the string where the tag is, has blank spaces and whether it has any special characters other than the ones in the alphabet.

Giving it a second thought, and after the engineer in the class said that tags can be compound words and have special characters and numbers such as Internet Explorer or 'google-chrome' or HTML5 I decided to modify this tiny script.

The problem is that I have no experience whatsoever on building regular expressions.

How can I do a regular expression with the following criteria?

  • Compound words
  • Dash special character in the middle of two words (internet-explorer, google-chrome)
  • No white spaces at the beginning or end of the string

这是一个满足您要求的PHP正则表达式:

/^\b[-a-z \d]*\b$/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM