php - convert single quoted string to double quoted

怎甘沉沦 提交于 2019-12-01 22:47:13

PHP does not have a standard safe way to do this, right now. There has been an open feature request for years asking for it: http://bugs.php.net/bug.php?id=43901

One of the comments on the ticket offers a regex to do simple $foo and ${foo} substitution:

function stringExpand($subject, array $vars) {
  foreach ($vars as $name => $value) {
    $subject = preg_replace(sprintf('/\$\{?%s\}?/', $name), $value, $subject);
  }
  return $subject;
}

If you know the names of the variables you want to replace you can do this...

$myname = 'david';
$occupation = 'Beginner';
$result = 'Hello my name is $myname and I my occupation is $occupation';

$result = str_replace( 
              array('$myname', '$occupation'),  
              array($myname, $occupation),
              $result );

Which will be quicker than Nathan's stringExpand function, but if you don't know the variable names, then do use Nathan's method.

The problem I was trying to solve when I found this question was to do with linebreaks in a csv feed and was solved something like this:

// string from drupals csv feed tamper settings
$string = '22 Acacia Avenue\n Irlam\n Manchester'; 
$string = str_replace('\n', "\n", $string);
print nl2br($string); // demonstrates that the \n's are now linebreak characters

You could do something like this:

<?php
$myname = 'david';
$occupation = 'Beginner';
eval("\$result = 'Hello my name is $myname and I my occupation is $occupation';");
echo $result;
?>

However, I strongly DO NOT recommended evaluating any code from a database. Anything out of your control is a security risk.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!