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生成zip压缩文件的方法详解

复制代码 代码如下:require_once "./include/zip.php"; $zip = new PHPZip(); //$zip -> createZip("要压缩的...

php字符串过滤strip_tags()函数用法实例分析

本文实例讲述了php字符串过滤strip_tags()函数用法。分享给大家供大家参考,具体如下: strip_tags — 从字符串中去除 HTML 和 PHP 标记,非常重要的函数 (...

解析ajax事件的调用顺序

jquery的ajax请求方法:复制代码 代码如下:$.ajax({          ...

PHP三层结构(下) PHP实现AOP第1/2页

PHP三层结构(下) PHP实现AOP第1/2页

本文源码下载地址:http://xiazai.jb51.net/201007/yuanma/TraceLWord.rar 开发环境为 eclipse(pdt) 让我们把注意力集中到中间服...

php字符串函数学习之strstr()

复制代码 代码如下: <?php /* 定义和用法 strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。 该函数返回字符串的其余部分(从匹配点)。如果未找到所...