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使用str_replace替换多维数组的实现方法分析

本文实例讲述了php使用str_replace替换多维数组的实现方法。分享给大家供大家参考,具体如下: 在php中,如果使用str_replace替换数组中的字符串,只能替换一维的数组,...

PHP大文件切割上传功能实例分析

PHP大文件切割上传功能实例分析

本文实例讲述了PHP大文件切割上传功能。分享给大家供大家参考,具体如下: 大家都知道php上传文件有限制,如果没有修改过php.ini文件的话,默认的上传大小限制为2M,那么该如何上传大...

PHP 实用代码收集

1. 可阅读随机字符串 此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。 复制代码 代码如下: /************** *@length - le...

php新建文件的方法实例

php文件如何新建?具体步骤如下: 在桌面空白处单击右键 -> 新建 -> 文本文件。 双击打开此文本文件后,在里面输入PHP代码,输入完后,选择文件 -> 另存为.....

Windows下编译PHP5.4和xdebug全记录

实际上我最终目的是编译得到支持 PHP5.4 的 php_xdebug.dll,而在此之前,成功编译 PHP5.4 是必须的。 编译环境以及相关软件包: 1.Microsoft Visu...