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与jquery设置和读取cookies

HTTP协议是一种无状态协议,这意味着你对网站的每一个请求都是独立的,而且因此无法通过它自身保存数据。但这种简单性也是它在互联网早期就广泛传播的原因之一。不过,它仍然有一种方法能让你用c...

PHP基于swoole多进程操作示例

PHP基于swoole多进程操作示例

本文实例讲述了PHP基于swoole多进程操作。分享给大家供大家参考,具体如下: 多个任务同时执行 将顺序执行的任务,转化为并行执行(任务在逻辑上可以并行执行) 比如,我们要对已知的用户...

php判断目录存在的简单方法

PHP判断文件或目录是否存在 file_exists:判断文件是否存在 $file = "check.txt"; if(file_exists($file)) { echo...

PHP模块 Memcached功能多于Memcache

比如说PECL里有两个Memcached的模块,Memcache和Memcached,目前大部分PHP环境里使用的是名字里不带d的Memcache版本,这个版本释出的比较早,是一个原生版...

php设计模式 Delegation(委托模式)

复制代码 代码如下: <?php /** * 委托模式 示例 * * @create_date: 2010-01-04 */ class PlayList { var $_song...