php正则preg_replace_callback函数用法实例

yipeiwu_com6年前PHP代码库

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

相关文章

php中file_get_contents()函数用法实例

我们先来看一下php中的 file_get_contents()函数的语法 string file_get_contents(string $ filename,bool $ inc...

php SQL之where语句生成器

复制代码 代码如下://生成where字符串 function get_where($arg = null) { foreach ((array)$arg as $key => $...

如何打开php的gd2库

如何打开php的gd2库

第一步:找到 php.ini 通常,该文件在php安装目录下,如果忘记路径可以在你使用的web服务软件上查询。 第二步:用记事本打开该文件,并按 “ctrl+F” 输入 “extens...

PHP结合Vue实现滚动底部加载效果

前言 最近的一个项目手机端分页跳转不理想,自己做了一个滚动加载的一个Demo,下面话不多说了,来一起看看详细的介绍吧。 实现思路      1....

PHP 七大优势分析

虽然ASP是一种不错的技术,但从长远考虑我相信PHP在将来的技术领域里会有不凡的表现。   我认为有七个理由可以说明PHP比ASP更优秀:   1、速度、速度、速度   当我第一次运行P...