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防止CC攻击代码 php防止网页频繁刷新

网页快速恶意刷新,cc攻击就是攻击者利用代理服务器生成指向目标站点的合法请求,模拟多用户不停的对受害网站进行访问,特别是访问那些需要大量数据操作需要大量CUP时间的页面,最终导致目标网站...

百度工程师讲PHP函数的实现原理及性能分析(二)

百度工程师讲PHP函数的实现原理及性能分析(二)

类方法 类方法其执行原理和用户函数是相同的,也是翻译成opcodes顺次调用。类的实现,zend用一个数据结构zend_class_entry来实现,里面保存了类相关的一些基本信息。这个...

windows下配置php5.5开发环境及开发扩展

网上的教程是比较多的,但是我发现在windows下的扩展开发比较少,而且大多都是php5.3版本以前的,今天我就给大家讲解一下php扩展开发,我就拿php5.5的版本来说明一下的了 wi...

PHP回调函数及匿名函数概念与用法详解

本文实例讲述了PHP回调函数及匿名函数概念与用法。分享给大家供大家参考,具体如下: 1、回调函数 PHP的回调函数其实和C、Java等语言的回调函数的作用是一模一样的,都是在主线程执行的...

php快速排序原理与实现方法分析

本文实例讲述了php快速排序方法。分享给大家供大家参考,具体如下: <?php $n = array('13','14','55','10','54','2','79'...