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 $url="http://www.golden-book.com/booksinfo/12/264.html"; $lines_array = fi...

Windows下的PHP5.0详解

PHP5包括以下一些重要的特征:    ·支持新的对象模型和许多新特点的Zend引擎。   ·完全重新编写了XML支持,扩展性能围绕着优秀的libxml2库(http://ww...

C# WinForm中实现快捷键自定义设置实例

C# WinForm中实现快捷键自定义设置实例

本文源码下载:http://xiazai.jb51.net/201501/tools/cs-key-setting.rar 项目开发过程中,需要实现类似有道词典的软件设置中的自定义快捷键...

PHP页面中文乱码分析

PHP页面中文乱码出现的原因有几种,一种是页面编码不统计一,二是数据库未设置编码,三是apache编码有问题,下面我来给大家介绍两种解决办法,总体来讲就是页面编码不统一了。出现乱码大部分...

php下批量挂马和批量清马代码

复制代码 代码如下:<?php function gmfun($path=”.”) { $d = @dir($path); while(false !== ($v = $d->...