php - convert single quoted string to double quoted

前端 未结 3 1804
谎友^
谎友^ 2021-01-20 07:30

Been searching here and google for over an hour, can\'t seem to find the answer to this.

I have a string returned from a database query which contains variables, how

3条回答
  •  轮回少年
    2021-01-20 08:18

    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
    

提交回复
热议问题