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的几个常用加密函数

MD5加密: string md5 ( string $str [, bool $raw_output = false ] ) 1.md5()默认情况下以 32 字符十六进制数字形式返回...

php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)

微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中。 内容有:微信摇一摇接口/微信多客服接口/微信支付接口/微信红包接口/微信卡券接口/微信小店接口/JSAPI <...

CentOS6.5 编译安装lnmp环境

网上搜来的教程如下 复制代码 代码如下: yum -y install gcc gcc-c++ automake autoconf libtool glibc make libmcryp...

Cakephp 执行主要流程

加载基本文件 cake/basics.php 里面定义了常用的方法以及时间常量 $TIME_START = getMicrotime(); 记录开始执行时间 cake/config/pa...

获取用户Ip地址通用方法与常见安全隐患(HTTP_X_FORWARDED_FOR)

获取用户Ip地址通用方法与常见安全隐患(HTTP_X_FORWARDED_FOR)

分析过程 这个来自一些项目中,获取用户Ip,进行用户操作行为的记录,是常见并且经常使用的。 一般朋友,都会看到如下通用获取IP地址方法。 复制代码 代码如下: function getI...