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中filter函数验证、过滤用户输入的数据

PHP Filter 简介 PHP 过滤器用于对来自非安全来源的数据(比如用户输入)进行验证和过滤。 复制代码 代码如下: //除去html标签,或除去编码特殊字符 var_dump(f...

如何使用脚本模仿登陆过程

查看他的登陆页面的代码, 看他提交到哪个页面, 变量是什么。复制代码 代码如下:<form method="post" action="lo...

PHP依赖注入容器知识点浅析

依赖注入容器理解 耦合 一个好的代码结构设计一定是松耦合的,这也是很多通用设计模式的宗旨,就是把分散在各处的同一个功能的代码汇聚到一起,形成一个模块,然后在不同模块之间通过一些细小的、明...

PHP常见字符串操作函数与用法总结

本文实例讲述了PHP常见字符串操作函数与用法。分享给大家供大家参考,具体如下: 一、字符串的格式化 1、字符串的格式化 trim()函数可以去除字符串的开始位置和结束位置的空格,并将结果...

PHP单元测试框架PHPUnit用法详解

本文实例讲述了PHP单元测试框架PHPUnit用法。分享给大家供大家参考,具体如下: 以前在学习IOS开发时有专门写过Objective-C的单元测试的文章,IOS开发学习之单元测试,...