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程序设计有所帮助。

相关文章

详解提高使用Java反射的效率方法

详解提高使用Java反射的效率方法

在我们平时的工作或者面试中,都会经常遇到“反射”这个知识点,通过“反射”我们可以动态的获取到对象的信息以及灵活的调用对象方法等,但是在使用的同时又伴随着另一种声音的出现,那就是“反射”很...

PHP创建word文档的方法(平台无关)

本文实例讲述了PHP创建word文档的方法。分享给大家供大家参考,具体如下: 关于用PHP生成word,在网上找了很多资料,有调用COM组件生成的,有安装PHP扩展生成的。都不免麻烦,以...

php jq jquery getJSON跨域提交数据完整版

前端请求端: 复制代码 代码如下: <script> $(function() { $.getJSON('http://test.com/aa.php?callback=?'...

openPNE常用方法分享

复制代码 代码如下: <?php include_partial('sidemenu',array('form'=>'asdfgasgsad'));?>这句话意思是包含...

php插入中文到sqlserver 2008里出现乱码的解决办法分享

今天使用php操作数据库时发现插入SQL Server 2008数据库里的中文字段出现乱码,下面是我一开始时的一些情况: 开发环境是php5.3.3+Apache2.2.17+SQL S...