正则表达式和撇号


regex and apostrophe

我的回答几乎是这样的:至少匹配3个字母,并匹配减号和撇号

所以,我也需要一个regex的名称验证。但是我的规则有点不同:

  • 必须以字母开头;
  • 无数字,无字母数字;
  • 必须至少有三个字母(也不仅是连续的…
  • 只能接受一个撇号('),或者不能接受其他的-这是唯一可以使用的特殊字符…(不是强制性的,也没有名字)。不管你把撇号

    放在哪里为例:

    d'amico =>必须接受;
    D 'amico' =>不D " amico => no我不知道Dell 'amore =>是的Damico =>是的金刚=>是的IO =>否Io9 => no
    8888 =>否aaa + + + ?

到现在为止,我有这个代码:

<?php
...
    // Array errori
    $error = array(); // o $error = []; se hai una versione di php recente
    // Controllo il Nome Utente
    if(trim($nome) == ''){
        $error[] = 'Campo nome non compilato'; }
    if (ctype_alnum($nome)) 
        {$error[] = 'Se vuoi modificare il campo nome, assicurati che lo 
             stesso non contenga numeri al suo interno!'; }  
    if(strlen($nome) < 3 || strlen($nome) > 20){
        $error[] = 'Il campo nome deve contenere minimo 3 caratteri e massimo 20 caratteri'; }
    if (!preg_match("/^([A-Za-z|àèéìòù][A-Za-z'-]*?){3,}$/", $nome)) {
        $error[] = 'Il campo nome contiene caratteri non ammessi'; } 
...
?>
<html>...
<?php 
      if(!empty($error)){
         echo  '<center>';
         echo implode('<br/>', $error);
        echo  '</center>';
      }
   ?>
...
</html>

如何将所有内容组合成一个字符串?提前感谢!

使用负向前看,您可以断言字符串不以'、空格或包含2个(或更多)单引号开始。然后你可以用你允许的字符列表测试字符串长度在3到20个字符之间。

(?!(.*?'.*?'|^[' ]))^[A-Za-z|àèéìòù ']{3,20}$

Regex演示:https://regex101.com/r/QANVBo/1

PHP Demo: https://eval.in/659769 PHP使用方法:

$array = array("d'amico", "dell'amore", "damico", "king kong", "io", "io9", "8888", "aaa+++?", "d'amico'", "d''amico", "'oneil");
foreach ($array as $term ) {
     if(preg_match("/(?!(.*?'.*?'|^[' ]))^[A-Za-z|àèéìòù ']{3,20}$/", $term)) {
          echo 'Matches:';
     } else {
          echo 'No Match:';
     }
     echo $term . "'n";
}