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 2.0如何使用页面缓存方法示例

前言 本文主要给大家介绍的是关于Yii2.0如何使用页面缓存的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍。 起初使用页面缓存,发现使用于含有参数的方法存在弊端,只能缓存第...

php empty() 检查一个变量是否为空

empty — 检查一个变量是否为空 Report a bug 描述 bool empty ( mixed $var ) 如果 var 是非空或非零的值,则 empty() 返回 FAL...

PHP+Ajax简单get验证操作示例

PHP+Ajax简单get验证操作示例

本文实例讲述了PHP+Ajax简单get验证操作。分享给大家供大家参考,具体如下: 1、显示页面代码 index.html <!DOCTYPE html> <htm...

PHP程序员学习使用Swoole的理由

PHP程序员学习使用Swoole的理由

最近两个月一直在研究 Swoole,研究成果即将在6.21正式开源发布,这段时间没有来水文章,趁着今天放假来水水吧。 借助这篇文章,我希望能够把 Swoole 安利给更多人。虽然 Swo...

利用PHP获取访客IP、地区位置、浏览器及来源页面等信息

前言 本文中主要介绍了关于利用PHP获取访客IP、地区位置、浏览器及来源页面等信息的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 不多说了,每个方法都注释了,可以直接用:...