首页 >后端开发 >php教程 >php正则preg_replace_callback函数的用法

php正则preg_replace_callback函数的用法

怪我咯
怪我咯原创
2017-07-06 10:40:341798浏览

这篇文章主要介绍了php正则preg_replace_callback函数用法,实例分析了preg_replace_callback函数进行正则替换的相关技巧,需要的朋友可以参考下

本文实例讲述了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 &#39;<b>&#39; . $Key . &#39;</b>: &#39; . $Value;
}
// The regular expression will extract and pass all "key: value" pairs to
// the "RewriteText" function that is definied above
$NewText = preg_replace_callback(&#39;/[\r\n]([a-z0-9]+): ([^\n\r]+)/i&#39;, "RewriteText", $Text);
// Print the new modified text
print $NewText;

以上是php正则preg_replace_callback函数的用法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn