note 40019 added to function.preg-replace

From: Date: Thu, 19 Feb 2004 03:43:56 +0000
Subject: note 40019 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-65368@lists.php.net to get a copy of this message
In regards to what daniil at nycfoto dot com shows us above, I used very similar types of template replacements with preg_replace. But for those of you who use this method, be careful with variable interpolation! See the below code snippet. <?php // the string we'll perform preg_replace on, we'll // replace <template> with something... $template = 'Start - <template> - End'; // the replacement (note that $1 is not interpolated, yet...) $content = 'Give me $1,000 please'; // perform replacement & print to show result print preg_replace('/<template>/', $content, $template); // output: "Start - Give me ,000 please - End" !!! ?> This caused me loads of problems initially, when people enter $ signs (eg: prices)... I don't know why it interpolates the $1 when preg_replace is performed... The only way I have found to change the $content line to this: <? $content = str_replace('$', '\$', 'Give me $1,000 please'); ?> But some people would recommend not use to preg_replace for simple string replacements (as it's slower to use preg_replace) you could use str_replace function instead. See contrasting example that does not perform variable interpolation: <?php // the string we'll perform preg_replace on, we'll // replace <template> with something... $template = 'Start - <template> - End' . "\n"; // the replacement (note that $1 is not interpolated, yet...) $content = 'Give me $1,000 please'; // perform replacement & print to show result print str_replace('<template>', $content, $template); // output: "Start - Give me $1,000 please - End" !!! ?> I hope this helps somebody! If anyone can tell me why preg_replace interpolates variables let me know! ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40019 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40019&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40019&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65368) next »