note 87390 deleted from language.types.string by cmb
| From: | cmb@php.net | Date: | Thu, 18 Nov 2021 12:56:19 +0000 |
| Subject: | note 87390 deleted from language.types.string by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217264@lists.php.net to get a copy of this message | ||
Note Submitter: cvolny at gmail dot com
----
I commented on a php bug feature request for a string expansion function and figured I should post
somewhere it might be useful:
using regex, pretty straightforward:
<?php
function stringExpand($subject, array $vars) {
// loop over $vars map
foreach ($vars as $name => $value) {
// use preg_replace to match ${
$name} or $$name
$subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value,
$subject);
}
// return variable expanded string
return $subject;
}
?>
using eval() and not limiting access to only certain variables (entire current symbol table
including [super]globals):
<?php
function stringExpandDangerous($subject, array $vars = array(), $random = true) {
// extract $vars into current symbol table
extract($vars);
$delim;
// if requested to be random (default), generate delim, otherwise use predefined (trivially
faster)
if ($random)
$delim = '___' . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . chr(mt_rand(65,90)) .
chr(mt_rand(65,90)) . chr(mt_rand(65,90)) . '___';
else
$delim = '__ASDFZXCV1324ZXCV__'; // button mashing...
// built the eval code
$statement = "return <<<$delim\n\n" . $subject . "\n$delim;\n";
// execute statement, saving output to $result variable
$result = eval($statement);
// if eval() returned FALSE, throw a custom exception
if ($result === false)
throw new EvalException($statement);
// return variable expanded string
return $result;
}
?>
I hope that helps someone, but I do caution against using the eval() route even if it is tempting.
I don't know if there's ever a truely safe way to use eval() on the web, I'd rather
not use it.