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请求远程地址设置超时时间,主要讲解file_get_contents、fopen、curl这三个简单常用函数设置超时时间的方法,一般情况下建议使用curl,性能最好,效率也最高。...

Mac下php 5升级到php 7的步骤详解

前言 在MAC OS X 10.11中php的版本是5.5的,近来一年多里,看到了很多关于php7介绍,以为php7增加了很多新特性,也删除了原来很多的老特性,所以一直以来并没想去尝试使...

thinkphp框架实现删除和批量删除

thinkphp框架实现删除和批量删除

本文实例讲一下如何用thinkphp实现数据的删除和批量删除吧。 预期效果图:   原谅博主对照片的处理是如此的草率吧。。。 仍然是 通过MVC模式进行拆分: 首先是视图部...

提高Laravel应用性能方法详解

使用Laravel做开发是高效而愉悦的体验。 通常,当你准备部署应用的时候,你可能会意识到应用也许会在真实环境下表现不佳。 需要明白的是,没有银弹。通过努力去对应用的每个细节完成所有的优...

PHP如何根据文件头检测文件类型实例代码

前言 什么是文件头部Bom? 说白了,就是在保存文件的时候,文件前面会多出一串隐藏的字符,文件签名一般都在文件的头部,如果你用十六进制方式查看文件,你就可以看到文件的一些签名信息。如用u...