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开发的文字水印,缩略图,图片水印实现类与用法。分享给大家供大家参考,具体如下: 1.实现类ImageToTest.class.php参考代码 class Imag...

PHP通过header实现文本文件下载的代码

这就是今天讨论的主要问题。PHP帮助文档里面关于PHP通过header触发下载的说明比较简单,而网上关于此方面的文章也少的可怜,有很多文章都无法实现所需要的效果。今天我也来谈一下这个方面...

将二维数组转为一维数组的2种方法

如何将下面的二维数组转为一维数组。 复制代码 代码如下:$msg = array(  array(    'id'=>'45',    'name'=>'jack'  ), ...

php中定时计划任务的实现原理

根据php手册简单介绍一些相关的知识: 1.连接处理: 在 PHP 内部,系统维护着连接状态,其状态有三种可能的情况: 0 - NORMAL(正常) 1 - ABORTED(异常退出)...

PHP字符串比较函数strcmp()和strcasecmp()使用总结

比较字符串是任何编程语言的字符串处理功能中重要的特性之一。在PHP中除了可以使用比较运算符号(==、<或>)加以比较外,还提供了一系列的比较函数,使PHP可以进行更复杂的字符...