当前位置:首页 > PHP教程 > PHP高级教程

php正则preg_replace_callback函数用法实例

本文实例讲述了php正则preg_replace_callback函数的用法。分享给大家供大家参考。具体实现方法如下:

php正则表达式功能强大,本范例演示了preg_replace_callback函数的用法

// define a dummy text, for testing...
$text = "title: hello world!n";
$text .= "author: jonasn";
$text .= "this is a example message!nn";
$text .= "title: entry 2n";
$text .= "author: sonjan";
$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 
  // --> ([^nr]+)
  $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('/[rn]([a-z0-9]+): ([^nr]+)/i', "rewritetext", $text);
// print the new modified text
print $newtext;

希望本文所述对大家的php程序设计有所帮助。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!