当前位置: 移动技术网 > IT编程>开发语言>PHP > php正则preg_replace_callback函数用法实例

php正则preg_replace_callback函数用法实例

2018年06月22日  | 移动技术网IT编程  | 我要评论

倾世情缘答题器,ca1625,建宁公主

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网