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开发中的tips(必看篇)

一、开发习惯和php代码 1、准确的理解各种概念。现在的新东西层出不穷,望文生义和一知半解对开发工作有害无益;//比如我就碰到有人理解松散耦合(这个东西不新)的概念居然是要求代码不要有空...

PHP set_error_handler()函数使用详解(示例)

我们写程序,难免会有问题(是经常会遇到问题 ),而PHP遇到错误时,就会给出出错脚本的位置、行数和原因。有很多人说,这并没有什么大不了。确实,在调试程序阶段,这确实是没啥的,而且我认为给...

PHP开发中四种查询返回结果分析

1.<!--使用mysql_result()来获取数据--> 复制代码 代码如下: <?php $connection=mysql_connect("localhost...

PHP的Trait机制原理与用法分析

本文实例讲述了PHP的Trait机制原理与用法。分享给大家供大家参考,具体如下: Trait介绍: 1、自PHP5.4起,PHP实现了一种代码复用的方法,称为trait。 2、Trait...

PHP面向对象之旅:深入理解static变量与方法

static关键字声明一个属性或方法是和类相关的,而不是和类的某个特定的实例相关,因此,这类属性或方法也称为“类属性”或“类方法”。 如果访问控制权限允许,可不必创建该类对象而直接使用类...