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 ss7.5的数据调用 (笔记)

php ss7.5的数据调用 (笔记)

这几天搞 ss7.5 dz7.2 uc1.5 uchome2.0和自己主站的整合 头都大了 呵呵  好歹是弄的差不多 了 呵呵 记录一下 ss7.5的数据调用  ...

PHP中Notice错误常见解决方法

对于初学者,肯定会遇到不同的错误提示,比如:警告,致命,等等,其中NOTICE错误等级最低,页面中,好多类似 Notice: Use of undefined constant titl...

php 时间time与日期date之间的使用详解及区别

php时间time与日期date之间的使用区别 1、time()函数 PHP中的time()函数,使用echo输出来看是一个很长的整数,里面包含了日期和时间,是计算后的一个值。如果要得...

20个PHP常用类库小结

图表库 下面的类库可以让你很简的创建复杂的图表和图片。当然,它们需要GD库的支持。 pChart - 一个可以创建统计图的库。 Libchart - 这也是一个简...

php5.2.0内存管理改进

php5.2.0的内存管理做了较大的改进,某些情况下内存不能释放的问题不存在了。测试php脚本(mem.php),我用echo N>>和sleep来控制脚本在某个阶...