Showing posts with label regexp. Show all posts
Showing posts with label regexp. Show all posts

Thursday, April 7, 2011

PHP ereg 正则表达式_景安数据李怀丽_新浪博客

PHP ereg 正则表达式_景安数据李怀丽_新浪博客

通常上, 正则表达式会用到以下的几个"符号":
^ - 代表字串前面一定要有这样的字, 如^http://, 代表前面一定要有http://
$ - 代表字串后面一定要有这样的字.
? (一个问号) - 它代表一个或没有字元
* (一个*) - 它代表没有或者更多前面的字元
. (一个句点) - 它代表任何一个字元
+ (一个加)
- 它代表至少一个或更多前面的字元
[xyz] - 它代表任何一个字元, 或x, 或y, 或z
[a-z] - 它代表任何一个字元, 由a至z
[[:alnum:]] - 代表由a至z, 0至9
[[:digit:]] - 代表由0至9

当使用正则表达式时, 必需注意ereg及eregi可大大不同喔~
ereg是非常敏感的 (意即大小字母都分得非常清楚), 而eregi则不是 (只要记着i代表case-insensitive就可以了)

这里举一些例子:

$regexp = eregi("a?c", "abc"); //-- 这是对的, 因?可以代表"一个"或没有字元
$regexp = eregi("a?c", "ac"); //-- 这也是对的, 因?可以代表一个或"没有"字元
$regexp = eregi("a?c", "a"); //-- 这样就不对了, 纵使有a, 可是还是要有c

$regexp = eregi("[abc]", "a"); //-- 这是对的, 因a是大括号里的其中一个字元
$regexp = eregi("[a-z]", "c"); //-- 这是对的, 因c包括在a至z里
$regexp = eregi("[a-z]", "0"); //-- 这是不对的, 因0并不包括在a至z里面

$regexp = eregi("a.c", "abc"); //-- 这是对的, 因一个.代表"任何"一个字
$regexp = eregi("a.c", "ac"); //-- 这可就不对了, 因.代表"一个"字元, 所以放abbc也是不对的

$regexp = eregi("a+c", "aaaac"); //-- 这是对的, 因+代表一人或"更多"前面的字元
$regexp = eregi("a+c", "abbc"); //-- 这样是不对的, +代表一个或更多"前面的字元", 而不是代表任何一个字元
$regexp = eregi("a+c", "abc"); //-- 这样也是不对的, 注释如上

$regexp = eregi("[^abc]", "a"); //-- 这是比较不同的一点, 那就是如果^出现在[]里面, 代表"除"了里面的字, 全部都是对的.
$regexp = eregi("[^abc]", "d"); //-- 这是对的, 因d并不在abc里面
$regexp = eregi("[^[:alnum:]]", "9"); //--这是对的, 因~并不包括在a至z, 0至9里面
当然, [[:digit:]]用法也是相同:
$regexp = eregi("[^[:digit:]]", "a"); //-- 这是对的, 因a并不包括在0至9里面

最后, 举个有用的例子,
比如说, 我要每个人的密码都不准拥有0至9, 可以这样试验:
$regexp = eregi("^[^0-9]+$", "aaa9"); //--把aaa9当做密码
if ($regexp == "") {
echo "密码拥有号码, 请改过";
} else {
echo "密码没有号码, 通过";
}

测验显示, 密码拥有号码, 请改过.
相信每个人都看到, [^0-9]前后各有^及$, 这是为了确保前后不能拥有号码, 而+则确保中间没有任何的号码,
[]里面的^, 则是"除了0至9之外, 其他一律通过"
所以只要将9拿去, 就会显示"密码没有号码, 通过"了 !

Using Regular Expressions with PHP

Using Regular Expressions with PHP

Regular expressions are a powerful tool for examining and modifying text. Regular expressions themselves, with a general pattern notation almost like a mini programming language, allow you to describe and parse text. They enable you to search for patterns within a string, extracting matches flexibly and precisely. However, you should note that because regular expressions are more powerful, they are also slower than the more basic string functions. You should only use regular expressions if you have a particular need.
This tutorial gives a brief overview of basic regular expression syntax and then considers the functions that PHP provides for working with regular expressions.
PHP supports two different types of regular expressions: POSIX-extended and Perl-Compatible Regular Expressions (PCRE). The PCRE functions are more powerful than the POSIX ones, and faster too, so we will concentrate on them.
The Basics
In a regular expression, most characters match only themselves. For instance, if you search for the regular expression "foo" in the string "John plays football," you get a match because "foo" occurs in that string. Some characters have special meanings in regular expressions. For instance, a dollar sign ($) is used to match strings that end with the given pattern. Similarly, a caret (^) character at the beginning of a regular expression indicates that it must match the beginning of the string. The characters that match themselves are called literals. The characters that have special meanings are called metacharacters.
The dot (.) metacharacter matches any single character except newline (\). So, the pattern h.t matches hat, hothit, hut, h7t, etc. The vertical pipe (|) metacharacter is used for alternatives in a regular expression. It behaves much like a logical OR operator and you should use it if you want to construct a pattern that matches more than one set of characters. For instance, the pattern Utah|Idaho|Nevada matches strings that contain "Utah" or "Idaho" or "Nevada". Parentheses give us a way to group sequences. For example, (Nant|b)ucket matches "Nantucket" or "bucket". Using parentheses to group together characters for alternation is called grouping.
If you want to match a literal metacharacter in a pattern, you have to escape it with a backslash.
To specify a set of acceptable characters in your pattern, you can either build a character class yourself or use a predefined one. A character class lets you represent a bunch of characters as a single item in a regular expression. You can build your own character class by enclosing the acceptable characters in square brackets. A character class matches any one of the characters in the class. For example a character class [abc] matches a, b or c. To define a range of characters, just put the first and last characters in, separated by hyphen. For example, to match all alphanumeric characters: [a-zA-Z0-9]. You can also create a negated character class, which matches any character that is not in the class. To create a negated character class, begin the character class with ^: [^0-9].
The metacharacters +, *, ?, and {} affect the number of times a pattern should be matched. + means "Match one or more of the preceding expression", * means "Match zero or more of the preceding expression", and ? means "Match zero or one of the preceding expression". Curly braces {} can be used differently. With a single integer, {n} means "match exactly n occurrences of the preceding expression", with one integer and a comma, {n,} means "match n or more occurrences of the preceding expression", and with two comma-separated integers {n,m} means "match the previous character if it occurs at least n times, but no more than m times".
Now, have a look at the examples:
Regular Expression Will match...
foo The string "foo"
^foo "foo" at the start of a string
foo$ "foo" at the end of a string
^foo$ "foo" when it is alone on a string
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any character that is not a uppercase letter
(gif|jpg) Matches either "gif" or "jpeg"
[a-z]+ One or more lowercase letters
[0-9\.\-] Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
([wx])([yz]) wy, wz, xy, or xz
[^A-Za-z0-9] Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers
Perl-Compatible Regular Expressions emulate the Perl syntax for patterns, which means that each pattern must be enclosed in a pair of delimiters. Usually, the slash (/) character is used. For instance, /pattern/.
The PCRE functions can be divided in several classes: matching, replacing, splitting and filtering.
Back to top
Matching Patterns
The preg_match() function performs Perl-style pattern matching on a string. preg_match() takes two basic and three optional parameters. These parameters are, in order, a regular expression string, a source string, an array variable which stores matches, a flag argument and an offset parameter that can be used to specify the alternate place from which to start the search:
preg_match ( pattern, subject [, matches [, flags [, offset]]])
The preg_match() function returns 1 if a match is found and 0 otherwise. Let's search the string "Hello World!" for the letters "ll":

if (preg_match("/ell/", "Hello World!", $matches)) {
  echo "Match was found
";

  echo $matches[0];
}
?>


The letters "ll" exist in "Hello", so preg_match() returns 1 and the first element of the $matches variable is filled with the string that matched the pattern. The regular expression in the next example is looking for the letters "ell", but looking for them with following characters:
if (preg_match("/ll.*/", "The History of Halloween", $matches)) {
  echo "Match was found
";
  echo $matches[0];
}
?>
Now let's consider more complicated example. The most popular use of regular expressions is validation. The example below checks if the password is "strong", i.e. the password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit:
$password = "Fyfjk34sdfjfsjq7";

if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) {
    echo "Your passwords is strong.";
} else {
    echo "Your password is weak.";
}
?>

The ^ and $ are looking for something at the start and the end of the string. The ".*" combination is used at both the start and the end. As mentioned above, the .(dot) metacharacter means any alphanumeric character, and * metacharacter means "zero or more". Between are groupings in parentheses. The "?=" combination means "the next text must be like this". This construct doesn't capture the text. In this example, instead of specifying the order that things should appear, it's saying that it must appear but we're not worried about the order.

The first grouping is (?=.*{8,}). This checks if there are at least 8 characters in the string. The next grouping (?=.*[0-9]) means "any alphanumeric character can happen zero or more times, then any digit can happen". So this checks if there is at least one number in the string. But since the string isn't captured, that one digit can appear anywhere in the string. The next groupings (?=.*[a-z]) and (?=.*[A-Z]) are looking for the lower case and upper case letter accordingly anywhere in the string.

Finally, we will consider regular expression that validates an email address:
$email = firstname.lastname@aaa.bbb.com;
$regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";

if (preg_match($regexp, $email)) {
    echo "Email address is valid.";
} else {
    echo "Email address is not valid.";
}
?>
This regular expression checks for the number at the beginning and also checks for multiple periods in the user name and domain name in the email address. Let's try to investigate this regular expression yourself.
For the speed reasons, the preg_match() function matches only the first pattern it finds in a string. This means it is very quick to check whether a pattern exists in a string. An alternative function, preg_match_all(), matches a pattern against a string as many times as the pattern allows, and returns the number of times it matched.
Back to top
Replacing Patterns
In the above examples, we have searched for patterns in a string, leaving the search string untouched. The preg_replace() function looks for substrings that match a pattern and then replaces them with new text. preg_replace() takes three basic parameters and an additional one. These parameters are, in order, a regular expression, the text with which to replace a found pattern, the string to modify, and the last optional argument which specifies how many matches will be replaced.

preg_replace( pattern, replacement, subject [, limit ])