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中的外观模式facade pattern

关于facade这个词的翻译 facade这个词,原意指的是一个建筑物的表面、外观,在建筑学中被翻译为“立面”这个术语,国内对facade这个词的关注,可能更多要依赖于laravel的...

php自定义函数实现统计中文字符串长度的方法小结

本文实例讲述了php自定义函数实现统计中文字符串长度的方法。分享给大家供大家参考,具体如下: 中文字符计算为2个字符 英文字符计算为1个 代码 /** * 可以统计中文字符串长度的...

动易数据转成dedecms的php程序

PS:这个可以举一反三,如新云或NB等asp文章系统都可转为dedecms或其它php的cms 复制代码 代码如下:<?php  //读取mdb数据库例程&nb...

采用header定义为文件然后readfile下载(隐藏下载地址)

复制代码 代码如下:<?php function sendFile($fileName, $fancyName = '', $forceDownload = true, $spee...

PHP与SQL注入攻击防范小技巧

下面来谈谈SQL注入攻击是如何实现的,又如何防范。  看这个例子: 复制代码 代码如下: // supposed input $name = "ilia'; DELETE FROM us...