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>