note 40019 deleted from function.preg-replace by nlopess
| From: | nlopess@php.net | Date: | Thu, 19 Feb 2004 13:41:23 +0000 |
| Subject: | note 40019 deleted from function.preg-replace by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-65392@lists.php.net to get a copy of this message | ||
Note Submitter: phpx @t badfont d0t c0m
----
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!