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实现的同步推荐操作API接口案例分析

本文实例分析了PHP实现的同步推荐操作API接口。分享给大家供大家参考,具体如下: 文档 1. 功能 同步推荐关系 2. 接口方法 syncRelation 3. 参数描述 Origin...

PHP内部实现打乱字符串顺序函数str_shuffle的方法

PHP内部实现打乱字符串顺序函数str_shuffle的方法

前言 2019年春节已过,今天是上班第一天,还得翻一翻之前没有看完的PHP源码。 今天聊的是字符串顺序打乱函数str_shuffle。这个函数本身使用频率并不高。但是,其内部实现还是非常...

php中$_SERVER[PHP_SELF] 和 $_SERVER[SCRIPT_NAME]之间的区别

“PHP_SELF” 当前正在执行脚本的文件名,与 document root 相关。举例来说,在 URL 地址为 //www.jb51.net/test.php/foo.bar 的脚本...

PHP并发多进程处理利器Gearman使用介绍

PHP并发多进程处理利器Gearman使用介绍

工作中我们有时候会遇到比如需要同时发布数据到多个个服务器上,或者同时处理多个任务。可以使用PHP的curl_multi的方式并发处理请求,但是由于网络和数据以及各个服务器等等的一些情况导...

PHP读取文本文件并逐行输出该行使用最多的字符与对应次数的方法

本文实例讲述了PHP读取文本文件并逐行输出该行使用最多的字符与对应次数的方法。分享给大家供大家参考,具体如下: test.txt文件: Welcome to our website...