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高手需要要掌握的知识点

如果想进入大的企业进行底层开发的话必须对互联网各方面的技术原理了解的很清楚,例如apache实现原理。语言方面既然是php开发自然对 c/c++要求比较高。往往需要自己写php扩展。使用...

Php header()函数语法及使用代码

语法:复制代码 代码如下:Void header(string $string[,bool $replace=true [, int $http_response_code)向客户端发送...

PHP字符编码问题之GB2312 VS UTF-8解决方法

PHP字符编码问题之GB2312 VS UTF-8解决方法

看代码: 复制代码 代码如下: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www...

学习php设计模式 php实现单例模式(singleton)

学习php设计模式 php实现单例模式(singleton)

保证一个类仅有一个实例,并且提供一个访问它的全局访问点。 单例模式有三个特点: 1、一个类只有一个实例 2、它必须自行创建这个实例 3、必须自行向整个系统提供这个实例 一、单例模式结构图...

PHP基于GD2函数库实现验证码功能示例

PHP基于GD2函数库实现验证码功能示例

本文实例讲述了PHP基于GD2函数库实现验证码功能。分享给大家供大家参考,具体如下: 在正式制作验证码之前要先补充点知识,PHP使用GD2函数库实现对各种图形图像的处理,所以我们制作验证...