Match only a word, or a hyphenated word

I am trying to use preg_match for form validation. The Regex needs to match any input that doesn't contain only characters, and characters followed by a hyphen also followed by more characters.

In other words the regex should catch any input that isn't a word made up of characters [az] and a hyphenated word (where there exists only one hyphen in the middle).

The regex should also catch words with a trailing hyphen (without another word following the hyphen eg "hello-") and should also catch words with a starting hyphen (eg "-hello").

Any help would be greatly appreciated.


Try the following code - if I understand your question, this will match only john-smith , which is what you want. Note - this is almost exactly what @Wrikken proposed in an earlier comment.

<?php
$test = array("john-smith", "123john", "john-", "john and mary smith");
$regex = '/^([a-z]+(?:-[a-z]+)?)$/i';
foreach($test as $t) {
  if(preg_match($regex, $t, $m)) {
    echo "$t matches!n";
  }
}
?>

See demo at

http://regex101.com/r/aU3qM0

链接地址: http://www.djcxy.com/p/76718.html

上一篇: 替换:替换使用%

下一篇: 只匹配一个字或连字符