php mixed preg_replace_callback 实例应用代码
2013-09-05 19:01
441 查看
php教程 mixed preg_replace_callback 实例应用代码
//需求:在所有连接后面添加一个request=xxx; 这个函数比preg_replace灵活性更强,要注意它所替换的内容为整个正则表达式的内容。
$content = 'http://www.php100.com/aaa.php?id=111">链接2';
function add_source($matches)
{
if(strpos($matches[1], '?'))
{
return 'href="'.$matches[1].'&request=xxx"'; //注意,这里和下面都加上了正则里括号外的东西:href="
}
else
{
return 'href="'.$matches[1].'?request=xxx"';
}
}
$content = preg_replace_callback('/href=['|"](.*?)['|"]/', 'add_source', $content);
//实例二
// 此文本是用于 2002 年的,
// 现在想使其能用于 2003 年
$text = "april fools day is 04/01/2002n";
$text.= "last christmas was 12/24/2001n";
// 回调函数
function next_year($matches) {
// 通常:$matches[0] 是完整的匹配项
// $matches[1] 是第一个括号中的子模式的匹配项
// 以此类推
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(d{2}/d{2}/)(d{4})|",
"next_year",
$text);
// 结果为:
// april fools day is 04/01/2003
// last christmas was 12/24/2002
//需求:在所有连接后面添加一个request=xxx; 这个函数比preg_replace灵活性更强,要注意它所替换的内容为整个正则表达式的内容。
$content = 'http://www.php100.com/aaa.php?id=111">链接2';
function add_source($matches)
{
if(strpos($matches[1], '?'))
{
return 'href="'.$matches[1].'&request=xxx"'; //注意,这里和下面都加上了正则里括号外的东西:href="
}
else
{
return 'href="'.$matches[1].'?request=xxx"';
}
}
$content = preg_replace_callback('/href=['|"](.*?)['|"]/', 'add_source', $content);
//实例二
// 此文本是用于 2002 年的,
// 现在想使其能用于 2003 年
$text = "april fools day is 04/01/2002n";
$text.= "last christmas was 12/24/2001n";
// 回调函数
function next_year($matches) {
// 通常:$matches[0] 是完整的匹配项
// $matches[1] 是第一个括号中的子模式的匹配项
// 以此类推
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(d{2}/d{2}/)(d{4})|",
"next_year",
$text);
// 结果为:
// april fools day is 04/01/2003
// last christmas was 12/24/2002
相关文章推荐
- php中常用的正则表达式的介绍及应用实例代码
- php使用str_replace替换多维数组的实现代码实例
- 采用CakePHP框架为Android应用快速搭建Web Service服务器及API接口的PHP代码实例
- 145 php 设计模式代码和应用场景实例
- php中常用的正则表达式的介绍及应用实例代码
- 利用discuz实现PHP大文件上传应用实例代码
- php google地图应用实例代码
- php反射应用实例代码
- redis 在PHP中的应用 代码实例
- 利用discuz实现PHP大文件上传应用实例代码
- php 搜索框提示(自动完成)实例代码
- PHP程序中使用adodb连接不同数据库的代码实例
- mysql分库分表实战及php代码操作完整实例
- php5.5新数组函数array_column应用实例分享
- php根据身份证号码计算年龄的实例代码
- php中使用redis队列操作实例代码
- php验证码代码实例
- PHP Memcached应用实现代码
- php实现页面纯静态的实例代码