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 无限级分类学习参考之对ecshop无限级分类的解析 带详细注释

复制代码 代码如下:function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset...

PHP基于cookie与session统计网站访问量并输出显示的方法

本文实例讲述了PHP基于cookie与session统计网站访问量并输出显示的方法。分享给大家供大家参考,具体如下: <?php $f_open = fopen("co...

php ignore_user_abort与register_shutdown_function 使用方法

语法: int ignore_user_abort(int [setting]); 返回值: 整数 函数种类: PHP 系统功能 内容说明 0 - NORMAL(正常)1 - ABORT...

PHP学习笔记(一) 简单了解PHP

PHP学习笔记(一) 简单了解PHP

目标规划: 通过第一节课,我们可以了解php环境. 1.环境的认识: 2.访问方法: 3.修改代码及查看. 4.变量的使用 5.代码缩进要有层次关系,而且代码之间最好保留空行 6.变量命...

php版交通银行网银支付接口开发入门教程

本文实例讲述了php版交通银行网银支付接口实现方法。分享给大家供大家参考,具体如下: 概述:网银支付接口 和支付宝接口大体上差不多,主要的区别是 交通银行提供的 接口核心的比如,加密等是...