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程序设计有所帮助。

相关文章

ajax返回值中有回车换行、空格的解决方法分享

ajax返回值中有回车换行、空格的解决方法分享

最近在写一个页面,用jquery ajax来实现判断,刚写好测试完全没有问题,过了两天发现出现问题,判断不成了。后来发现所有alert出来的返回值前面都会加若干换行和空格。(至今不明白,...

浅析ThinkPHP中的pathinfo模式和URL重写

复制代码 代码如下:http://serverName/appName/module/action/id/1/ 这个就是pathinfo模式 在不考虑路由的情况下,第一个参数会被解析成模...

在CentOS上搭建LAMP+vsftpd环境的简单指南

VPS 可以看成是一台只有你一个人使用的服务器(事实上它是一个虚拟机),你可以在上面安装任何软件,拥有最大的权限。正所谓权限越大,责任越大,你需要自行安装 Web 服务器,数据库,PHP...

php实现跨域提交form表单的方法【2种方法】

本文实例讲述了php实现跨域提交form表单的方法。分享给大家供大家参考,具体如下: 有时我们为了网站安全考虑,我们不允许直接跨域提交form表单数据,如果我们自己有这个需求呢?下面我们...

分割GBK中文遭遇乱码的解决方法

类似如下的字符串(GBK), explode不能得到正确结果: 1.$result = explode("|", "滕华弢|海青"); 究其原因, 对于”弢”字(读tao,不认识没关系,...