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 $var1 = "#####"; $var2 = "&&&&&"; function global_references($use...

setcookie中Cannot modify header information-headers already sent by错误的解决方法详解

复制代码 代码如下:<?php   setcookie("username","bu",time()+3600);   echo "aaaa...

php自动给文章加关键词链接的函数代码

复制代码 代码如下: <?php $link = array( '百度,http://www.baidu.com/', '服务器软件,http://s.jb51.net/', '【...

php多用户读写文件冲突的解决办法

一般的方案会是:复制代码 代码如下:$fp = fopen("/tmp/lock.txt", "w+");if (flock($fp, LOCK_EX)) {  &n...

Content-Disposition使用方法和注意事项

最近不少Web技术圈内的朋友在讨论协议方面的事情,有的说web开发者应该熟悉web相关的协议,有的则说不用很了解。个人认为这要分层次来看待这个问 题,对于一个新手或者刚入门的web开发人...