PHP正则表达式之2种模式和Cookie详解(代码实例)
正则表达式是一种强大的模式匹配工具,它可以实现对字符串的高效处理。在PHP中,我们可以使用正则表达式来完成字符串的搜索、替换、分割等常见操作。本文将介绍PHP正则表达式的两种模式和Cookie的详解,并提供实例代码供大家参考。
一、PHP正则表达式的两种模式
在PHP中,正则表达式有两种模式:分隔符模式和函数模式。
1. 分隔符模式
分隔符模式是PHP中最常用的正则表达式模式,它使用/作为分隔符。例如,我们可以使用如下代码来匹配字符串中的数字:
$str = 'Welcome to 2021'; $regex = '/\d+/'; preg_match_all($regex, $str, $matches); print_r($matches);
上述代码使用\d+正则表达式来匹配字符串中的数字,然后使用preg_match_all()函数进行匹配并输出结果。其中,preg_match_all()函数用于在字符串中查找所有匹配项。
2. 函数模式
函数模式是PHP中另一种常用的正则表达式模式,它使用preg_函数来完成正则表达式的匹配操作。例如,我们可以使用如下代码来匹配字符串中的链接:
$str = 'Visit our website: www.example.com'; $regex = '/\bwww\.[^\s]+/'; preg_match_all($regex, $str, $matches); print_r($matches);
上述代码使用\bwww\.[^\s]+正则表达式来匹配字符串中的链接,然后使用preg_match_all()函数进行匹配并输出结果。
二、Cookie的详解
Cookie是一种HTTP协议提供的机制,它可以通过在客户端保存一些数据来实现用户的状态管理和数据传递。在PHP中,我们可以使用setcookie()函数来设置Cookie,并使用$_COOKIE来读取客户端提交的Cookie。
1. 设置Cookie
我们可以使用如下代码来设置Cookie:
setcookie('username', 'Alice', time()+3600);
上述代码设置了一个名为username、值为Alice、过期时间为3600秒后的Cookie。
2. 读取Cookie
我们可以使用如下代码来读取Cookie:
echo $_COOKIE['username'];
上述代码输出了名为username的Cookie的值。
3. 删除Cookie
我们可以使用如下代码来删除Cookie:
setcookie('username', '', time()-3600);
上述代码删除了名为username的Cookie。
三、代码实例
下面是一个实际运用正则表达式和Cookie的PHP代码示例,该代码用于解析HTML页面中的链接并输出到页面中:
<?php
$url = 'http://www.example.com';
$html = file_get_contents($url);
// 匹配页面中的链接
$regex = '/<a\s[^>]*href="(.*?)"/i';
preg_match_all($regex, $html, $matches);
// 输出链接
foreach ($matches[1] as $link) {
if (strpos($link, 'http') !== false) {
echo '<a href="' . $link . '">' . $link . '</a><br>';
} else {
echo '<a href="' . $url . $link . '">' . $link . '</a><br>';
}
}
// 设置Cookie
setcookie('visited', true, time()+3600);
// 读取Cookie
if (isset($_COOKIE['visited'])) {
echo 'This page has been visited.';
}
// 删除Cookie
setcookie('visited', '', time()-3600);
?>
上述代码首先使用file_get_contents()函数将HTML页面读入到变量$html中,然后使用正则表达式匹配页面中的链接,最后输出链接到页面中。同时,代码还演示了如何使用setcookie()、$_COOKIE和删除Cookie。
