note 47735 added to function.preg-replace

From: Date: Sat, 27 Nov 2004 00:56:50 +0000
Subject: note 47735 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-81086@lists.php.net to get a copy of this message
If you want to use /e in the Reg expression, I think using escaped double quote is better than just single quote in the replacement parameter. I meet this problem when I try to replace a string that contains double quote in it, it cost me some time to solve this. So I simplified my code and present here: consider capitalize SSI directives in the input text: $html_body = "<!--#include virtual=\"header.htm\" -->"; //That is, source text: <!--#include virtual="header.htm" --> $html_body = preg_replace('/(<!--#)(.*)(-->)/e', "'\\1'.strtoupper('\\2').'\\3'", $html_body); echo $html_body; //output text: <!--#INCLUDE VIRTUAL=\"HEADER.HTM\" --> //Result is not what you want: there is additional backslash generated that is useless. My Solution to this: use \" instead of ', that make it a little mess, but garanteed working. $html_body = preg_replace('/(<!--#)(.*)(-->)/e', "\"\\1\".strtoupper(\"\\2\").\"\\3\"", $html_body); echo $html_body; //result is correct now: <!--#INCLUDE VIRTUAL="HEADER.HTM" --> ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+47735 Delete -- http://master.php.net/manage/user-notes.php?action=delete+47735&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47735&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47735&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47735&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47735&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47735&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+47735&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#81086) next »