Home > Backend Development > PHP Tutorial > PHP regular and js regular_PHP tutorial

PHP regular and js regular_PHP tutorial

WBOY
Release: 2016-07-13 17:53:11
Original
1051 people have browsed it


Regular expression function in PHP

There are two sets of regular expression function libraries in PHP. One set is provided by the PCRE (Perl Compatible Regular Expression) library. The PCRE library implements regular expression pattern matching using the same syntax rules as Perl, using functions named with the "preg_" prefix. The other set is provided by the POSIX (Portable Operation System interface) extension library. POSIX extended regular expressions are defined by POSIX 1003.2 and generally use functions named with the "ereg_" prefix.
The functions of the two sets of function libraries are similar, but the execution efficiency is slightly different. Generally speaking, to achieve the same function, the efficiency of using the PCRE library is slightly superior. Its use is described in detail below.


Regular expression matching
1. preg_match()
Function prototype: int preg_match (string $pattern, string $content [, array $matches])
The preg_match () function searches the $content string for content that matches the regular expression given by $pattern. If $matches is provided, the matching results are placed in it. $matches[0] will contain the text that matches the entire pattern, $matches[1] will contain the first captured match of the pattern element enclosed in parentheses, and so on. This function only performs one match and ultimately returns the number of matching results of 0 or 1. Listing 6.1 shows a code example for the preg_match() function.
Code 6.1 Date and time matching
//The string that needs to be matched. The date function returns the current time
$content = "Current date and time is ".date("Y-m-d h:i a").", we are learning PHP together.";
//Use the usual method to match time
If (preg_match ("/d{4}-d{2}-d{2} d{2}:d{2} [ap]m/", $content, $m))
{
echo "The matching time is:" .$m[0]. "n";
}
//Since the time pattern is obvious, it can also be matched simply
If (preg_match ("/([d-]{10}) ([d:]{5} [ap]m)/", $content, $m))
{
echo "The current date is:" .$m[1]. "n";
echo "The current time is:" .$m[2]. "n";
}
?>
This is a simple dynamic text string matching example. Assuming that the current system time is "13:25 on August 17, 2006", the following content will be output.
The matching time is: 2006-08-17 01:25 pm
The current date is: 2006-08-17
The current time is: 01:25 pm
2. ereg() and eregi()
ereg() is the regular expression matching function in the POSIX extension library. eregi() is a case-ignoring version of the ereg() function. Both have similar functions to preg_match, but the function returns a Boolean value indicating whether the match was successful or not. It should be noted that the first parameter of the POSIX extension library function accepts a regular expression string, that is, no delimiter is required. For example, Listing 6.2 is a method for checking the security of file names.
Code 6.2 Security check of file name
$username = $_SERVER['REMOTE_USER'];
$filename = $_GET['file'];
//Filter file names to ensure system security
If (!ereg('^[^./][^/]*$', $userfile))
{
​​​​​die('This is not an illegal file name!');
}
//Filter usernames
If (!ereg('^[^./][^/]*$', $username))
{
              die('This is not an invalid username');
}
                                                                    //Place file paths through security filtering
$thefile = "/home/$username/$filename";
?>
Typically, using the Perl-compatible regular expression matching function perg_match() will be faster than using ereg() or eregi(). If you just want to find whether a string contains a certain substring, it is recommended to use the strstr() or strpos() function.
3. preg_grep()
Function prototype: array preg_grep (string $pattern, array $input)
The preg_grep() function returns an array containing the cells in the $input array that match the given $pattern pattern. Preg_grep() also only performs a match for each element in the input array $input. The example given in Listing 6.3 simply illustrates the use of the preg_grep() function.
Code 6.3 Array query matching
$subjects = array(
"Mechanical Engineering", "Medicine",
"Social Science", "Agriculture",
"Commercial Science", "Politics"
);

//匹配所有仅由有一个单词组成的科目名
$alonewords = preg_grep("/^[a-z]*$/i", $subjects);
?>
6.3.2  进行全局正则表达式匹配
1.preg_match_all()
与preg_match()函数类似。如果使用了第三个参数,将把所有可能的匹配结果放入。本函数返回整个模式匹配的次数(可能为0),如果出错返回False。下面是一个将文本中的URL链接地址转换为HTML代码的示例。代码6.4是preg_match_all()函数的使用范例。
代码6.4  将文本中的链接地址转成HTML
//功能:将文本中的链接地址转成HTML
//输入:字符串
//输出:字符串
function url2html($text)
{
//匹配一个URL,直到出现空白为止
preg_match_all("/http:\/\/?[^\s]+/i", $text, $links);
//设置页面显示URL地址的长度
$max_size = 40;
foreach($links[0] as $link_url)
{
//计算URL的长度。如果超过$max_size的设置,则缩短。
$len = strlen($link_url);
if($len > $max_size)
             {
                 $link_text = substr($link_url, 0, $max_size)."...";
             } else {
                 $link_text = $link_url;
             }
             //生成HTML文字
             $text = str_replace($link_url,"$link_text",$text);
         }
         return $text;
     }
              
     //运行实例
     $str = “这是一个包含多个URL链接地址的多行文字。欢迎访问http://www.taoboor.com”;
     print url2html($str);
     /*输出结果
        这是一个包含多个URL链接地址的多行文字。欢迎访问
         http://www.taoboor.com

     */
?>
2.多行匹配
仅仅使用POSIX下的正则表式函数,很难进行复杂的匹配操作。例如,对整个文件(尤其是多行文本)进行匹配查找。使用ereg()对此进行操作的一个方法是分行处理。代码6.5的示例演示了ereg()如何将INI文件的参数赋值到数组之中。
代码6.5  文件内容的多行匹配
$rows = file('php.ini'); //将php.ini文件读到数组中
//循环遍历
foreach($rows as $line)
{
If(trim($line))
{
//将匹配成功的参数写入数组中
if(eregi("^([a-z0-9_.]*) *=(.*)", $line, $matches))
{
$options[$matches[1]] = trim($matches[2]);
}
unset($matches);
}
}
//输出参数结果
print_r($options);
?>
提示
这里只是为了方便说明问题。解析一个*.ini文件,最佳方法是使用函数parse_ini_file()。该函数直接将*.ini文件解析到一个大数组中。
6.3.3  正则表达式的替换
1.ereg_replace()和eregi_replace()
函数原型:string ereg_replace (string $pattern, string $replacement, string $string)
                                                                 string eregi_replace (string $pattern, string $replacement, string $string)
ereg_replace()在$string中搜索模式字符串$pattern,并将所匹配结果替换为$replacement。当$pattern中包含模式单元(或子模式)时,$replacement中形如“\1”或“$1”的位置将依次被这些子模式所匹配的内容替换。而“\0”或“$0”是指整个的匹配字符串的内容。需要注意的是,在双引号中反斜线作为转义符使用,所以必须使用“\\0”,“\\1”的形式。
eregi_replace()和ereg_replace()的功能一致,只是前者忽略大小写。代码6.6是本函数的应用实例,这段代码演示了如何对程序源代码做简单的清理工作。
代码6.6  源代码的清理
$lines = file('source.php'); //将文件读入数组中
for($i=0; $i<count($lines); $i++)
{
//将行末以“\\”或“#”开头的注释去掉
$lines[$i] = eregi_replace("(\/\/|#).*$", "", $lines[$i]);
//将行末的空白消除
$lines[$i] = eregi_replace("[ \n\r\t\v\f]*$", "\r\n", $lines[$i]);
}
//整理后输出到页面
echo htmlspecialchars(join("",$lines));
?>
2.preg_replace()
函数原型:mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit])
preg_replace较ereg_replace的功能更加强大。其前三个参数均可以使用数组;第四个参数$limit可以设置替换的次数,默认为全部替换。代码6.7是一个数组替换的应用实例。
代码6.7  数组替换
//字符串
$string = "Name: {Name}<br>\nEmail: {Email}
\nAddress: {Address}
\n";
     //模式
     $patterns =array(
             "/{Address}/",
             "/{Name}/",
             "/{Email}/"
    );
     //替换字串
     $replacements = array (
             "No.5, Wilson St., New York, U.S.A",
             "Thomas Ching",
             "tom@emailaddress.com",
     );
     //输出模式替换结果
     print preg_replace($patterns, $replacements, $string);
?>
输出结果如下。
Name: Thomas Ching",
Email: tom@emailaddress.com
Address: No.5, Wilson St., New York, U.S.A
在preg_replace的正则表达式中可以使用模式修正符“e”。其作用是将匹配结果用作表达式,并且可以进行重新运算。例如:
$html_body = “<HTML>

TEST

My Picture”;
     //输出结果中HTML标签将全部为小写字母
     echo preg_replace (
             "/(<\/?)(\w+)([^>]*>)/e",
             "'\\1'.strtolower('\\2').'\\3'",   //此处的模式变量\\2将被strtolower转换为小写字符
              $html_body);
?>
提示
preg_replace函数使用了Perl兼容正则表达式语法,通常是比ereg_replace更快的替代方案。如果仅对字符串做简单的替换,可以使用str_replace函数。
6.3.4  正则表达式的拆分
1.split()和spliti()
函数原型:array split (string $pattern, string $string [, int $limit])
本函数返回一个字符串数组,每个单元为$string经正则表达式$pattern作为边界分割出的子串。如果设定了$limit,则返回的数组最多包含$limit个单元。而其中最后一个单元包含了$string中剩余的所有部分。spliti是split的忽略大小版本。代码6.8是一个经常用到关于日期的示例。
代码6.8  日期的拆分
$date = "08/30/2006";

//分隔符可以是斜线,点,或横线
list($month, $day, $year) = split ('[/.-]', $date);

//输出为另一种时间格式
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>
2.preg_split()
本函数与split函数功能一致。代码6.9是一个查找文章中单词数量的示例。
代码6.9  查找文章中单词数量
$seek = array();
$text = "I have a dream that one day I can make it. So just do it, nothing is impossible!";

//将字符串按空白,标点符号拆分(每个标点后也可能跟有空格)
$words = preg_split("/[.,;!\s']\s*/", $text);
foreach($words as $val)
{
$seek[strtolower($val)] ++;
}
echo "共有大约" .count($words). "个单词。";
echo "其中共有" .$seek['i']. "个单词“I”。";
?>
提示
preg_split()函数使用了Perl兼容正则表达式语法,通常是比split()更快的替代方案。使用正则表达式的方法分割字符串,可以使用更广泛的分隔字符。例如,上面对日期格式和单词处理的分析。如果仅用某个特定的字符进行分割,建议使用explode()函数,它不调用正则表达式引擎,因此速度是最快的。


下面是一些讲解和例子,仅供大家参考和修改使用:

2. “^d+$”  //Non-negative integer (positive integer + 0)
3. "^[0-9]*[1-9][0-9]*$" //Positive integer
4. "^((-d+)|(0+))$" //Non-positive integer (negative integer + 0)
5. "^-[0-9]*[1-9][0-9]*$" //Negative integer
6. “^-?d+$”  //Integer
7. "^d+(.d+)?$"  //Non-negative floating point number (positive floating point number + 0)
8. "^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]* .[0-9]+)|([0-9]*[1-9][0-9]*))$" //Positive floating point number
9. "^((-d+(.d+)?)|(0+(.0+)?))$" //Non-positive floating point number (negative floating point number + 0)
10. "^(-(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9 ]*.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //Negative floating point number
11. "^(-?d+)(.d+)?$" //Floating point number
12. "^[A-Za-z]+$"  //A string consisting of 26 English letters
13. "^[A-Z]+$" //A string consisting of 26 uppercase English letters
14. "^[a-z]+$" //A string consisting of 26 lowercase English letters
15. "^[A-Za-z0-9]+$" // A string consisting of numbers and 26 English letters
16. "^w+$" //A string consisting of numbers, 26 English letters or underscores
17. "^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$" //email address
18. "^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(?S*)?$" //url
19. /^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([ 1-9]{1}))|(3[0|1]))$/ // Year-month-day
20. /^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3 [0|1]))/(d{2}|d{4})$/ // month/day/year
21. "^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.) |(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$" //Emil
22. /^((+?[0-9]{2,4}-[0-9]{3,4}-)|([0-9]{3,4}-))?([0 -9]{7,8})(-[0-9]+)?$/ //Phone number
23. "^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[ 0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d| 25[0-5])$" //IP address
24. 
25. Regular expression to match Chinese characters: [u4e00-u9fa5]
26. Match double-byte characters (including Chinese characters): [^x00-xff]
27. Regular expression to match blank lines: n[s| ]*r
28. Regular expression to match HTML tags: /<(.*)>.*|<(.*) />/
29. Regular expression matching leading and trailing spaces: (^s*)|(s*$)
30. Regular expression to match email address: w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
31. Regular expression to match URL: ^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\? \S*)?$
32. Whether the matching account is legal (starting with a letter, 5-16 bytes allowed, alphanumeric underscores allowed): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$
33. Match domestic phone numbers: (d{3}-|d{4}-)?(d{8}|d{7})?
34. Matching Tencent QQ number: ^[1-9]*[1-9][0-9]*$
35. 
36. 
37. Metacharacters and their behavior in the context of regular expressions:
38. 
39. Mark the next character as a special character, a literal character, a backreference, or an octal escape character.
40. 
41. ^ matches the beginning of the input string. If the Multiline property of the RegExp object is set, ^ also matches the position after 'n' or 'r'.
42. 
43. $ matches the end position of the input string. If the Multiline property of the RegExp object is set, $ also matches the position before 'n' or 'r'.
44. 
45. * Matches the previous subexpression zero or more times.
46. 
47. + Matches the previous subexpression one or more times. + is equivalent to {1,}.
48. 
49. ? Match the previous subexpression zero or one time. ? Equivalent to {0,1}.
50. 
51. {n} n is a non-negative integer that matches a certain number of n times.
52. 
53. {n,} n is a non-negative integer that matches at least n times.
54. 
55. {n,m} m and n are both non-negative integers, where n <= m. Match at least n times and at most m times. There cannot be a space between the comma and the two numbers.
56. 
57. ? When the character immediately follows any other limiter (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. Non-greedy mode matches as little of the searched string as possible, while the default greedy mode matches as much of the searched string as possible.
58. 
59. . Matches any single character except "n". To match any character including 'n', use a pattern like '[.n]'.
60. (pattern) matches pattern and gets this match.
61. 
62. (?:pattern) matches pattern but does not obtain the matching result, which means that this is a non-acquisition match and is not stored for later use.
63. 
64. (?=pattern) Forward lookup, matches the search string at the beginning of any string that matches pattern. This is a non-fetch match, that is, the match does not need to be fetched for later use.
65. 
66. (?!pattern) negative preview, opposite to (?=pattern)
67. 
68. x|y matches x or y.
69. 
70. [xyz] character set.
71. 
72. [^xyz] Negative value character set.
73. 
74. [a-z] character range, matches any character within the specified range.
75. 
76. [^a-z] Negative character range, matches any character that is not within the specified range.
77. 
78. b matches a word boundary, which refers to the position between a word and a space.
79. 
80. B matches non-word boundaries.
81. 
82. cx matches the control character specified by x.
83. 
84. d matches a numeric character. Equivalent to [0-9].
85. 
86. D matches a non-numeric character. Equivalent to [^0-9].
87. 
88. f matches a form feed character. Equivalent to x0c and cL.
89. 
90. n matches a newline character. Equivalent to x0a and cJ.
91. 
92. r matches a carriage return character. Equivalent to x0d and cM.
93. 
94. s matches any whitespace character, including spaces, tabs, form feeds, etc. Equivalent to [fnrtv].
95. 
96. S matches any non-whitespace character. Equivalent to [^ fnrtv].
97. 
98. t matches a tab character. Equivalent to x09 and cI.
99. 
100. v matches a vertical tab character. Equivalent to x0b and cK.
101. 
102. w matches any word character including an underscore. Equivalent to '[A-Za-z0-9_]'.
103. 
104. W matches any non-word character. Equivalent to '[^A-Za-z0-9_]'.
105. 
106. xn matches n, where n is the hexadecimal escape value. The hexadecimal escape value must be exactly two digits long.
107. 
108. num matches num, where num is a positive integer. A reference to the match obtained.
109. 
110. n identifies an octal escape value or a backreference. n is a backreference if n is preceded by at least n fetched subexpressions. Otherwise, if n is an octal number (0-7), then n is an octal escape value.
111. 
112. nm identifies an octal escape value or a backreference. If nm is preceded by at least nm fetched subexpressions, nm is a backreference. If nm is preceded by at least n gets, then n is a backreference followed by the literal m. If neither of the previous conditions is true, and if n and m are both octal digits (0-7), nm will match the octal escape value nm.
113. 
114. nml If n is an octal digit (0-3), and m and l are both octal digits (0-7), then matches the octal escape value nml.
115. 
116. un matches n, where n is a Unicode character represented by four hexadecimal digits.
117. 
118. Regular expression to match Chinese characters: [u4e00-u9fa5]
119. 
120. Match double-byte characters (including Chinese characters): [^x00-xff]
121. 
122. Regular expression to match blank lines: n[s| ]*r
123. 
124. Regular expression to match HTML tags: /<(.*)>.*|<(.*) />/
125. 
126. Regular expression matching leading and trailing spaces: (^s*)|(s*$)
127. 
128. Regular expression to match email address: w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
129. 
130. Regular expression to match URL: http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?
131. 
132. Use regular expressions to limit the input content of text boxes in web forms:
133. 
134. Use regular expressions to limit input to Chinese only: onkeyup="value=value.replace(/[^u4E00-u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData( 'text').replace(/[^u4E00-u9FA5]/g,''))"
135. 
136. Use regular expressions to limit the input of only full-width characters: onkeyup="value=value.replace(/[^uFF00-uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData ('text').replace(/[^uFF00-uFFFF]/g,''))"
137. 
138. Use regular expressions to limit input to numbers: onkeyup="value=value.replace(/[^d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text ').replace(/[^d]/g,''))"
139. 
140. Use regular expressions to limit input to numbers and English only: onkeyup="value=value.replace(/[W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData(' text').replace(/[^d]/g,''))"
141. 
142. =========Commonly used regular expressions
143. 
144. 
145. 
146. Regular expression to match Chinese characters: [u4e00-u9fa5]
147. 
148. Match double-byte characters (including Chinese characters): [^x00-xff]
149. 
150. Regular expression to match blank lines: n[s| ]*r
151. 
152. Regular expression to match HTML tags: /<(.*)>.*|<(.*) />/
153. 
154. Regular expression matching leading and trailing spaces: (^s*)|(s*$)
155. 
156. Regular expression to match IP address: /(d+).(d+).(d+).(d+)/g //
157. 
158. Regular expression to match email address: w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
159. 
160. Regular expression to match URL: http://(/[w-]+.)+[w-]+(/[w- ./?%&=]*)?
161. 
162. sql statement: ^(select|drop|delete|create|update|insert).*$
163. 
164. 1. Non-negative integer: ^d+$
165. 
166. 2. Positive integer: ^[0-9]*[1-9][0-9]*$
167. 
168. 3. Non-positive integers: ^((-d+)|(0+))$
169. 
170. 4. Negative integers: ^-[0-9]*[1-9][0-9]*$
171. 
172. 5. Integer: ^-?d+$
173. 
174. 6. Non-negative floating point number: ^d+(.d+)?$
175. 
176. 7. Positive floating point number: ^((0-9)+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0 -9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$
177. 
178. 8. Non-positive floating point numbers: ^((-d+.d+)?)|(0+(.0+)?))$
179. 
180. 9. Negative floating point number: ^(-((positive floating point number regular expression)))$
181. 
182. 10. English string: ^[A-Za-z]+$
183. 
184. 11. English capital string: ^[A-Z]+$
185. 
186. 12. English lowercase string: ^[a-z]+$
187. 
188. 13. English character and number string: ^[A-Za-z0-9]+$
189. 
190. 14. Alphanumeric plus underline string: ^w+$
191. 
192. 15. E-mail address: ^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$
193. 
194. 16. URL: ^[a-zA-Z]+://(w+(-w+)*)(.(w+(-w+)*))*(?s*)?$
195. Or: ^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]':+!]*([ ^<>""])*$
196. 
197. 17. Postal code: ^[1-9]d{5}$
198. 
199. 18. Chinese: ^[u0391-uFFE5]+$
200. 
201. 19. Phone number: ^(((d{2,3}))|(d{3}-))?((0d{2,3})|0d{2,3}-)?[1 -9]d{6,7}(-d{1,4})?$
202. 
203. 20. Mobile phone number: ^(((d{2,3}))|(d{3}-))?13d{9}$
204. 
205. 21. Double-byte characters (including Chinese characters): ^x00-xff
206. 
207. 22. Match leading and trailing spaces: (^s*)|(s*$) (trim function like vbscript)
208. 
209. 23. Match HTML tags: <(.*)>.*|<(.*) />
210. 
211. 24. Match blank lines: n[s| ]*r
212. 
213. 25. Extract network links in the information: (h|H)(r|R)(e|E)(f|F) *= *('|")?(w|\|/|.)+ ('|"| *|>)?
214. 
215. 26. Extract the email address in the information: w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
216. 
217. 27. Extract the picture link in the information: (s|S)(r|R)(c|C) *= *('|")?(w|\|/|.)+('|"| *|>)?
218. 
219. 28. Extract the IP address in the information: (d+).(d+).(d+).(d+)
220. 
221. 29. Extract the Chinese mobile phone number in the information: (86)*0*13d{9}
222. 
223. 30. Extract the Chinese fixed phone number in the information: ((d{3,4})|d{3,4}-|s)?d{8}
224. 
225. 31. Extract Chinese phone numbers (including mobile and landline phones) from the information: ((d{3,4})|d{3,4}-|s)?d{7,14}
226. 
227. 32. Extract the Chinese postal code in the information: [1-9]{1}(d+){5}
228. 
229. 33. Extract floating point numbers (i.e. decimals) in the information: (-?d*).?d+
230. 
231. 34. Extract any number in the information: (-?d*)(.d+)?
232. 
233. 35. IP: (d+).(d+).(d+).(d+)
234. 
235. 36. Telephone area code: /^0d{2,3}$/
236. 
237. 37. Tencent QQ number: ^[1-9]*[1-9][0-9]*$
238. 
239. 38. Account number (starting with a letter, allowing 5-16 bytes, allowing alphanumeric underscores): ^[a-zA-Z][a-zA-Z0-9_]{4,15}$
240. 
241. 39. Chinese, English, numbers and underline: ^[u4e00-u9fa5_a-zA-Z0-9]+$


js regular function match, exec, test, search, replace, split usage introduction collection
js: pattern = /-+.*/
Pattern.test ('Your characters ‘) Return to BOOL value
Pattern.exec ('Your character') Return the array
str.replace(param1,param2) Note that param1 here can be a direct character or a regular expression. Param2 is the character you want to replace. Be sure to note that there is a return value. Your final replacement result is the return value

The following is a detailed introduction to some methods:
match method
Performs a search on a string using a regular expression pattern and returns the results containing the search as an array.
stringObj.match(rgExp)
Parameters
stringObj
Required. The String object or string literal to search for.
rgExp
Required. Is a regular expression object containing the regular expression pattern and available flags. Can also be a variable name or string literal containing a regular expression pattern and available flags.
The rest of the instructions are the same as exec, except that if the expression of match matches the global tag g, all matches will appear without looping, but all matches will not include submatches.
Example 1:
function MatchDemo(){ var r, re; // Declare variables. var s = "The rain in Spain falls mainly in the plain"; re = /(a)in/ig; // Create a regular expression pattern. r = s.match(re); // Try to match the search string. document.write(r); //The returned array contains all four occurrences of "ain", r[0], r[1], r[2], r[3]. // But there is no submatch a. }Output result: ain,ain,ain,ain


exec method

Search in a string using a regular expression pattern and return the first value (array) of the search result. If the match fails, return null.
rgExp.exec(str)
Parameters
rgExp
Required. A regular expression object containing the regular expression pattern and available flags.
str
Required. The String object or string literal in which to perform the search.
The returned array contains:
input: the value of the entire searched string;
index: the position (bit) of the matching result;
lastInput: the position of the next matching result;
arr: result value, arr[0] is the full matching result, arr[1,2...] is the submatch of () in the expression, from left to right is 1,2....
Example 2:
The code is as follows:

function RegExpTest(){
var src="http://sumsung753.blog.163.com/blog/I love you!";
var re = /w+/g; // Note that g will match the entire text. If not added, only the first match will always be returned.
var arr;
while((arr = re.exec(src)) !=null){ //exec causes arr to return the first match, and a while loop will cause re to look for the next match in g.
document.write(arr.index + "-" + arr.lastIndex + ":" + arr + "
");
for(key in arr){
document.write(key + "=>" + arr[key] + "
");
}
document.write("
");
}
}
window.onload = RegExpTest();

Output result:
0-1:I //0 is index, the position of i, 1 is the position of the next match
input=>I love you!
index=>0
lastIndex=>1
0=>I
2-6:love
input=>I love you!
index=>2
lastIndex=>6
0=>love
7-10:you
input=>I love you!
index=>7
lastIndex=>10
0=>you
Note: According to the manual, exec only returns the first value of the matching result. For example, if the while loop is not used in the above example, only 'I' will be returned (although love and you after the i space both conform to the expression), regardless of the re expression used The global flag g is not used. But if the global flag g is set for the regular expression, exec starts looking at the position indicated by the value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from the beginning of the string. Using this feature, you can call exec repeatedly to traverse all matches, which is equivalent to match having the g flag.
Of course, if you forget to use g in the regular expression and use loops (such as while, for, etc.), exec will loop the first one every time, causing an infinite loop.
The output of exec will contain submatches.
Example 3:
The code is as follows:

function execDemo(){
var r, re; // Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = /[w]*(ai)n/ig;
r = re.exec(s);
document.write(r + "
");
for(key in r){
document.write(key + "-" + r[key] + "
");
}
}
window.onload = execDemo();

Output:
rain,ai
input-The rain in Spain falls mainly in the plain
index-4
lastIndex-8
0-rain
1-ai

test method

Returns a Boolean value indicating whether the given regular expression is matched in the string being searched.
rgexp.test(str)
Parameters
rgexp
Required. A regular expression object containing a regular expression pattern or available flags.
str
Required. The string to test the lookup on.
Description
The test method checks whether the string matches the given regular expression pattern and returns true if it does, otherwise it returns false.
Example 4:
The code is as follows:

function TestDemo(re, s){
var s1;
if (re.test(s))
s1 = "match regular expression";
else
s1 = "Does not match regular expression";
return("'" + s + "'" + s1 + "'"+ re.source + "'");
}
window.onload = document.write(TestDemo(/ab/,'cdef'));

Output result: 'cdef' does not match the regular expression 'ab'
Note: test() inherits the lastIndex attribute of the regular expression. Pay attention when the expression matches the global flag g.
Example 5:
The code is as follows:

function testDemo(){
var r, re; // Declare variables.
var s = "I";
re = /I/ig; // Create a regular expression pattern.
document.write(re.test(s) + "
"); // Returns Boolean result.
document.write(re.test(s) + "
");
document.write(re.test(s));
}
testDemo();

Output result:
true
false
true
When test() is called for the second time, lastIndex points to the next matching position 1, so the second match is unsuccessful, and lastIndex points to 0 again, which means that the match is repeated for the third time. The following example shows the lastIndex attribute of test:
Example 6:
The code is as follows:

function testDemo(){
var r, re; // Declare variables.
var s = "I";
re = /I/ig; // Create a regular expression pattern.
document.write(re.test(s) + "
"); // Returns Boolean result.
document.write(re.lastIndex); // Return Boolean result.
}
testDemo();

Output:
true
1
Solution: Repoint the lastIndex attribute of test() to 0 each time, re.lastIndex = 0;

search method

Returns the position (offset bit) of the first substring matching the regular expression search content.
stringObj.search(rgExp)
Parameters
stringObj
Required. A String object or string literal to search on.
rgExp
Required. A regular expression object containing the regular expression pattern and available flags.
Description: If found, return the offset bit of the subcharacter to the beginning, otherwise return -1.
Example 6:
The code is as follows:

function SearchDemo(){
var r, re; // Declare variables.
var s = "The rain in Spain falls mainly in the plain.";
re = /falls/i; // Create a regular expression pattern.
re2 = /tom/i;
r = s.search(re); // Search for string.
r2 = s.search(re2);
return("r: " + r + "; r2: " + r2); // Returns a Boolean result.
}
document.write(SearchDemo());

Output: r: 18; r2: -1

replace method
Returns a copy of the string after literal replacement based on the regular expression.
stringObj.replace(rgExp, replaceText)
Parameters
stringObj
Required. The String object or string literal to perform this replacement on. The string will not be modified by the replace method.
rgExp
Required. Is a regular expression object containing a regular expression pattern or available flags. Can also be a String object or literal. If rgExp is not a regular expression object, it is converted to a string and an exact search is performed; do not attempt to convert the string to a regular expression.
replaceText
Required. Is a String object or string literal that replaces each matching position in rgExp in stringObj with the literal contained in the object. In Jscript 5.5 or newer, the replaceText parameter can also be a function that returns replacement text.
Description
The result of the replace method is a copy of the stringObj object with the specified replacement. It means that the matching items are replaced as specified, and the other items are returned unchanged as StringObj.
ECMAScript v3 stipulates that the parameter replacement of the replace() method can be a function instead of a string. In this case, the function is called for each match and the string it returns is used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern, and there can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself. The result is a string value with each matching substring replaced with the corresponding return value of the function call. Function parameters can perform more complex operations.
Example 7:
The code is as follows:

function f2c(s) {
var test = /(d+(.d*)?)Fb/g; // Indicates that the possible modes for Fahrenheit temperature are: 123F or 123.4F. Note that g mode is used here
return(s.replace
(test,
function(Regstr,$1,$2,$3,newstrObj) {
return(("
" + Regstr +"
" + ($1-32) * 1/2) + "C" +"
" + //The following Replace two lines
$2 +"
" + $3 +"
" + newstrObj +"
" );
}
)
);
}
document.write(f2c("Water: 32.2F and Oil: 20.30F."));

Output result:
Water: //Characters that do not match the regular expression are output as original characters
32.2F //The original string of the first string matching the regular expression Regstr
0.10000000000000142C //The replacement result of the first sub-pattern matching of the first string matching the regular expression $1
.2 //The replacement result of the second sub-pattern match of the first string that matches the regular expression, here we do not replace it $2
7 //The offset of the first submatch of the first string matching the regular expression $3
Water: 32.2F and Oil: 20.30F. //Original string newstrObj
and Oil: //Characters that do not match regular expressions
20.30F //The original string of the second string matching the regular expression
-5.85C //The first subpattern of the second string matching the regular expression and the matching replacement result
.30 //The replacement result of the second sub-pattern match of the second string matching the regular expression, here we do not replace it
22 //The offset of the first submatch of the second string matching the regular expression
Water: 32.2F and Oil: 20.30F. //Original string
. //Characters that do not match regular expressions
We have used all the function parameters above. In practice, we only need to replace xxF with xxC. According to the requirements, we do not need to write so many parameters.
Example 8:
The code is as follows:

function f2c(s) {
var test = /(d+(.d*)?)Fb/g; // Possible modes for Fahrenheit temperature are: 123F or 123.4F
return(s.replace
(test,
function(strObj,$1) {
return((($1-32) * 1/2) + "C");
}
)
);
}
document.write(f2c("Water: 32.2F and Oil: 20.30F."));

Output: Water: 0.10000000000000142C and Oil: -5.85C.
More apps:
Example 9:
The code is as follows:

function f2c(s) {
var test = /([d]{4})-([d]{1,2})-([d]{1,2})/;
return(s.replace
(test,
function($0,$1,$2,$3) {
return($2 +"/" + $1);
}
)
);
}
document.write(f2c("today: 2011-03-29"));

Output: today: 03/2011

split method
Splits a string into substrings and returns the result as an array of strings.
stringObj.split([separator[, limit]])
Parameters
stringObj
Required. The String object or literal to be decomposed. The object is not modified by the split method.
separator
Optional. A string or regular expression object that identifies whether one or more characters are used to separate the string. If this option is omitted, a single-element array containing the entire string is returned.
limit
Optional. This value is used to limit the number of elements in the returned array.
Description
The result of the split method is an array of strings, split at each occurrence of separator in stingObj. separator is not returned as part of any array element.
Example 10:
The code is as follows:

function SplitDemo(){
var s, ss;
var s = "The rain in Spain falls mainly in the plain.";
// Regular expression, separated by s, regardless of uppercase or lower case.
ss = s.split(/s/i);
return(ss);
}
document.write(SplitDemo());

Output: The rain in ,pain fall, mainly in the plain.

JS regular expression exec() method, match() method and search() method
Let’s look at the code first:

var sToMatch = "test, Tes, tst, tset, Test, Tesyt, sTes";
var reEs = /es/gi;
alert(reEs.exec(sToMatch));
alert(sToMatch.match(reEs));
alert(sToMatch.search(reEs));

The contents of the three pop-up boxes are as follows:

PHP regular and js regular_PHP tutorial

PHP regular and js regular_PHP tutorial

PHP regular and js regular_PHP tutorial

The results are analyzed as follows:

1. The exec() method of RegExp has a string parameter and returns an array. The first entry of the array is the first match; the others are back references. So the first result returned is the first matching value es (case insensitive). www.2cto.com

2. The String object has a match() method, which returns a data containing all matches in the string. This method calls the string object and passes it a RegExp object. So the second popup statement returns all arrays that match the regular expression.

3. The string method of search() is somewhat similar to indexOf(), but it uses a RegExp object instead of just a substring. The search() method returns the position of the first matching value. So what pops up at the third place is "1", that is, the second character matches. Note that the search() method does not support global matching regular expressions (with parameter g).

Author: wjc19911118

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478072.htmlTechArticleRegular expression functions in PHP There are two sets of regular expression function libraries in PHP. One set is provided by the PCRE (Perl Compatible Regular Expression) library. The PCRE library uses the same syntax as Perl...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template