php正则preg_replace_callback函数用法实例

yipeiwu_com5年前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求小于1000的所有水仙花数的代码

水仙花数是一个n(>=3)位数字的数, 它等于每个数字的n次幂之和. 例如, 153是一个水仙花数, 153=1³+5³+3³. 编写程序, 求解小于...

PHP中运用jQuery的Ajax跨域调用实现代码

可以在页面定义一个调用方法,如下: 复制代码 代码如下: function getData(){ $.getJSON("http://123.123.123.123/?callback=...

smarty缓存用法分析

本文详细分析了smarty缓存的用法。分享给大家供大家参考。具体分析如下: 一开始以为smarty只是用来做一些掩饰php代码功能,但是后来才知道还有模板缓存这个强大的功能。 什么是模板...

PHP实现自动识别Restful API的返回内容类型

如题,PHP如何自动识别第三方Restful API的内容,自动渲染成 json、xml、html、serialize、csv、php等数据? 其实这也不难,因为Rest API也是基于...

PHPMailer的主要功能特点和简单使用说明

支持邮件 s/mime加密的数字签名 支持邮件多个 TOs, CCs, BCCs and REPLY-TOs 可以工作在任何服务器平台,所以不用担心WIN平台无法发送邮件的问题的 支持文...