ลงทะเบียน
ใกล้กัน ช่วยให้คุณแชร์เรื่องราวต่างๆ กับผู้คนมากมาย

คนเขียนเว็บด้วย PHP, Javascript ชอบสิ่งนี้

การหาอีเมล์ในข้อความจำเป็นต้องสร้างประโยค Regular Expression เช่น "[/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/]"

 

MetacharacterDescriptionExample
. Matches any single character except a new line /./ matches anything that has a single character
^ Matches the beginning of or string / excludes characters /^PH/ matches any string that starts with PH
$ Matches pattern at the end of the string /com$/ matches guru99.com,yahoo.com Etc.
* Matches any zero (0) or more characters /com*/ matches computer, communication etc.
+ Requires preceding character(s) appear at least once /yah+oo/ matches yahoo
\ Used to escape meta characters /yahoo+\.com/ treats the dot as a literal value
[...] Character class /[abc]/ matches abc
a-z Matches lower case letters /a-z/ matches cool, happy etc.
A-Z Matches upper case letters /A-Z/ matches WHAT, HOW, WHY etc.
0-9 Matches any number between 0 and 9 /0-4/ matches 0,1,2,3,4

  The above list only gives the most commonly used metacharacters in regular expressions.

Let’s now look at a fairly complex example that checks the validity of an email address.

<?php
$my_email = "name@company.com";
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/", $my_email)) {
echo "$my_email is a valid email address";
}
else
{
  echo "$my_email is NOT a valid email address";
}
?>

 Explaining the pattern 

HERE,

  • "'/.../'" starts and ends the regular expression
  • "^[a-zA-Z0-9._-]" matches any lower or upper case letters, numbers between 0 and 9 and dots, underscores or dashes.
  • "+@[a-zA-Z0-9-]" matches the @ symbol followed by lower or upper case letters, numbers between 0 and 9 or dashes.
  • "+\.[a-zA-Z.]{2,5}$/" escapes the dot using the backslash then matches any lower or upper case letters with a character length between 2 and 5 at the end of the string.
Captcha Challenge
ลองรูปภาพใหม่
Type in the verification code above