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字符串操作针对负值的判断分析

本文实例分析了php字符串操作针对负值的判断方法。分享给大家供大家参考,具体如下: $a = '-1'; $b = (int)$a; $c = is_numeric($a); if...

php smarty 二级分类代码和模版循环例子

php smarty 二级分类代码和模版循环例子

二级分类的数据表结构如下: PHP代码如下 复制代码 代码如下: /** @ 文章分类 含二级分类 @ param int $rootnum -- 一级分类数量 @ param int...

PHP递归统计系统中代码行数

本文实例为大家分享了PHP递归统计系统中代码行数的具体代码,供大家参考,具体内容如下 1、统计代码行数,必然用到的两个关键的知识点:函数递归以及文件读取。 函数递归无非就是在函数的代码中...

php常用Output和ptions/Info函数集介绍

flush函数:刷新输出缓冲ob_clean函数:清空输出缓冲ob_end_clean函数:清空缓冲区并且关闭正在进行的输出缓冲ob_end_flush函数:发送缓冲区数据并且关闭缓冲区...

推荐Discuz!5的PHP代码高亮显示与实现可运行代码

discuz!5.0论坛显示风格的php代码高亮显示插件, 把php代码进行语法着色,喜欢PHP的同志可以轻松的看代码啦。 同时添加了html代码运行功能。 此插件是在以前某位同志发布的...