欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php正则preg_replace_callback函数用法实例

程序员文章站 2023-11-27 11:34:04
本文实例讲述了php正则preg_replace_callback函数的用法。分享给大家供大家参考。具体实现方法如下: php正则表达式功能强大,本范例演示了preg_r...

本文实例讲述了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程序设计有所帮助。