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生成不重复随机数、数组的4种方法分享

php生成不重复随机数、数组的4种方法分享

下面写几种生成不重复随机数的方法,直接上代码吧 复制代码 代码如下: <?php define('RANDOM_MAX', 100); define('COUNT', 10...

基于php实现长连接的方法与注意事项的问题

php可以通过set_time_limit(0);来取消php脚步超时限制,从而达到长连接的效果。 例子代码如下:复制代码 代码如下:<?php echo "每隔3秒输出一次<...

php empty()与isset()区别的详细介绍

在使用 php 编写页面程序时,我经常使用变量处理函数判断 php 页面尾部参数的某个变量值是否为空,开始的时候我习惯了使用 empty() 函数,却发现了一些问题,因此改用 isset...

支持汉转拼和拼音分词的PHP中文工具类ChineseUtil

PHP 中文工具类,支持汉字转拼音、拼音分词、简繁互转。 PHP Chinese Tool class, support Chinese pinyin, pinyin participl...

并发下常见的加锁及锁的PHP具体实现代码

在最近的项目中有这样的场景 1.生成文件的时候,由于多用户都有权限进行生成,防止并发下,导致生成的结果出现错误,需要对生成的过程进行加锁,只容许一个用户在一个时间内进行操作,这个时候就需...