php正则preg_replace_callback函数用法实例

yipeiwu_com6年前PHP代码库

本文实例讲述了php正则preg_replace_callback函数的用法。分享给大家供大家参考。具体实现方法如下:

php正则表达式功能强大,本范例演示了preg_replace_callback函数的用法

// Define a dummy text, for testing...
$Text = "Title: Hello world!\n";
$Text .= "Author: Jonas\n";
$Text .= "This is a example message!\n\n";
$Text .= "Title: Entry 2\n";
$Text .= "Author: Sonja\n";
$Text .= "Hello world, what's up!\n";
// This function will replace specific matches
// into a new form
function RewriteText($Match){
  // Entire matched section: 
  // --> /.../
  $EntireSection = $Match[0];
  // --> "\nTitle: Hello world!"
  // Key 
  // --> ([a-z0-9]+)
  $Key      = $Match[1];
  // --> "Title"
  // Value 
  // --> ([^\n\r]+)
  $Value    = $Match[2];
  // --> "Hello world!"
  // Add some bold (<b>) tags to around the key to
  return '<b>' . $Key . '</b>: ' . $Value;
}
// The regular expression will extract and pass all "key: value" pairs to
// the "RewriteText" function that is definied above
$NewText = preg_replace_callback('/[\r\n]([a-z0-9]+): ([^\n\r]+)/i', "RewriteText", $Text);
// Print the new modified text
print $NewText;

希望本文所述对大家的php程序设计有所帮助。

相关文章

php+redis在实际项目中HTTP 500: Internal Server Error故障排除

问题描述 用户量快速增长,访问量在短时间内翻倍,由于前期容量规划做得比较好,硬件资源可以支撑,可是软件系统方面出现了大问题: 40% 的请求都会返回 HTTP 500: Internal...

URL Rewrite的设置方法

URL Rewrite需要服务器的支持!在启用此设置之前,请确保服务器上已作出了正确的设置,设置方法请参看下边的“Apache下的设置方法”和“IIS下的设置方法”!Apach...

学习php开源项目的源码指南

一。先把源代码安装起来,结合它的文档和手册,熟悉其功能和它的应用方式。 二。浏览源代码的目录结构,了解各个目录的功能。 三。经过以上两步后相信你对这个开源的产品有了一个初步的了解了,那现...

PHP发送邮件确认验证注册功能示例【修改别人邮件类】

PHP发送邮件确认验证注册功能示例【修改别人邮件类】

本文实例讲述了PHP发送邮件确认验证注册功能。分享给大家供大家参考,具体如下: 类库: require "class.phpmailer.php"; require "class....

PHP CKEditor 上传图片实现代码

我花了一个下午的时间,自己用PHP脚本写了一个处理上传文件的脚本代码,没有做更多的安全处理,希望对大家有用。 首先,在你的config.js文件里添加如下代码: 复制代码 代码如下: C...