php正则preg_replace_callback函数用法实例

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

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

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

  1. // Define a dummy text, for testing...
  2. $Text = "Title: Hello world!\n";
  3. $Text .= "Author: Jonas\n";
  4. $Text .= "This is a example message!\n\n";
  5. $Text .= "Title: Entry 2\n";
  6. $Text .= "Author: Sonja\n";
  7. $Text .= "Hello world, what's up!\n";
  8. // This function will replace specific matches
  9. // into a new form
  10. function RewriteText($Match){
  11. // Entire matched section:
  12. // --> /.../
  13. $EntireSection = $Match[0];
  14. // --> "\nTitle: Hello world!"
  15. // Key
  16. // --> ([a-z0-9]+)
  17. $Key = $Match[1];
  18. // --> "Title"
  19. // Value
  20. // --> ([^\n\r]+)
  21. $Value = $Match[2];
  22. // --> "Hello world!"
  23. // Add some bold (<b>) tags to around the key to
  24. return '<b>' . $Key . '</b>: ' . $Value;
  25. }
  26. // The regular expression will extract and pass all "key: value" pairs to
  27. // the "RewriteText" function that is definied above
  28. $NewText = preg_replace_callback('/[\r\n]([a-z0-9]+): ([^\n\r]+)/i', "RewriteText", $Text);
  29. // Print the new modified text
  30. print $NewText;

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