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

相关文章

yii框架源码分析之创建controller代码

使用yii框架的url路径一般形如hostname/?r=xxxx/xxxx/xxxx&sdfs=dsfdsf 我们可以看到有时会使用protected目录下的controller,有时...

使用图灵api创建微信聊天机器人

使用图灵api创建微信聊天机器人

需要准备的资源: 图灵机器人账号 微信公共账号 点击访问 图灵机器人官网,快快注册,拥有自己的聊天机器人,可以在这里先体验一下 今天主要简述微信公共平台聊天机器人的搭建,首先需要注册微...

详解PHP序列化和反序列化原理

0.前言 对象的序列化和反序列化作用就不再赘述,php中序列化的结果是一个php自定义的字符串格式,有点类似json. 我们在任何语言中设计对象的序列化和反序列化都需要解决几个问题 把某...

php生成SessionID和图片校验码的思路和实现代码

/****** 产生Session ID ******/ 基本的思路: 是把当前微秒的时间获取, 然后产生以个随机数字, 把随机数字和当前时间相加后加密一下, 最后再截取需要的长度...

php设计模式 State (状态模式)

状态state模式是GOF23种模式中的一种,和命令模式一样,也是一种行为模式。状态模式和命令模式相当像,一样是“接口—实现类”这种模式的应用,是面向接口编程原则的体现。 状态模式属于对...