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如何统计Nginx日志的User Agent数据

利用PHP如何统计Nginx日志的User Agent数据

前言 即将用到爬虫,于是打算收集一下User Agent(UA)数据。接着马上想到自己网站的访问日志不就是现成的优质数据源吗?于是愉快的决定写个脚本统计一下Nginx访问日志中的UA信息...

php获取用户浏览器版本的方法

本文实例讲述了php获取用户浏览器版本的方法。分享给大家供大家参考。具体分析如下: 在php中我们有个全局变量$_SERVER['HTTP_USER_AGENT'];可以获取用户所有信息...

php中用数组的方法设置cookies

复制代码 代码如下: <?php         function set_cronology($name,$value,$duration...

php实现excel中rank函数功能的方法

本文实例讲述了php实现excel中rank函数功能的方法。分享给大家供大家参考。具体分析如下: sql语句实现排名是像这样的如: 总分成绩为 195,180,180,161,名次分别为...

WordPress中限制非管理员用户在文章后只能评论一次

之前有网友提出,在WordPress中有没有办法实现每篇文章只允许用户评论一次? 暂不说这个需求有没有用,毕竟WordPress就是给有各种需求的人用的。这个功能实现起来也比较简单,只需...