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

相关文章

lnmp安装多版本PHP共存的方法详解

lnmp安装多版本PHP共存的方法详解

通过lnmp安装了PHP7版本,但是发现与程序不兼容,需要降低到7.0以下的版本。 查找lnmp的install.sh文件,一般在/root/lnmp1.5/install.sh 下执行...

PHP最常用的正则表达式

一、校验数字的表达式 数字:^[0-9]*$ n位的数字:^\d{n}$ 至少n位的数字:^\d{n,}$ m-n位的数字:^\d{m,n}$ 零和非零开头的数字:^(0|[1-9][0...

PHP在线打包下载功能示例

PHP在线打包下载功能示例

本文实例讲述了PHP在线打包下载功能实现方法。分享给大家供大家参考,具体如下: 昨天晚上,为了弄这个打包下载的事,弄的事焦头烂额。有几个问题,第一个是开始PHP_ZIP.dll的问题。话...

FCKeditor的安装(PHP)

1.下载新最版的FCKEditor,解压 2.删除/FCKeditor/目录下除fckconfig.js, fckeditor.js, fckstyles.xml,&...

php cookie的操作实现代码(登录)

第一个文件login_frm.php这个是登录窗口 代码 复制代码 代码如下: <html> <head> <meta http-equiv="Conten...