2016-07-18 7 views
0

불행히도 나는 데이터베이스에 HTML 코드의 일부를 보관하고 변수로 렌더링하는 데 문제가 있습니다.문자열을 변수로 렌더링하는 방법은 무엇입니까?

public function myFunction() 
{ 
    //... 
    // example data 
    $data = array(
     'url' => 'example.com', 
     'value' => 'Go to website!' 
    ); 

    //Here I get html code from database, let's say it looks like this: 
    $htmlPart = "<a href='{$data['url']}'>{$data['value']}</a>"; 

    $html = // rendered $htmlPart with variables 

    return $html; 
} 

내가 할 경우 : 내 함수 내에서

echo $htmlPart; 

. 그것은 작동하지만, 렌더링 된 $ htmlPart 변수로 반환해야하지만 작동시키지 못합니다.

나는 심지어 위한 ob_start 사용하여 그것을 할 시도 : 나는

<a href="{$data['url']}"> 
    {$data['value']} 
</a> 

(이 렌더링되는 HTML을 얻을 :

ob_start(); 
echo $htmlPart 
$html = ob_get_contents(); 
ob_end_clean(); 

을하지만이 작동하지 않습니다, 여기 내가 무엇을 얻을 소스 코드에서)

내가 뭘 잘못하고 있니?

+0

왜 그렇죠 단지 VAR와 문자열 CONCAT? .. 옛날 방식으로, 알지? – Jeff

+0

그래서, 당신은 데이터베이스에 저장된'{$ data [ 'url']}'을 문자 그대로 * 값으로 대체하려고합니까? 문자열 (정규 표현식을 사용하여)을 구문 분석하고 값을 바꿔야합니다. –

+2

리터럴 문자열이라면 어떻게 설명할까요? "echo $ htmlPart'를 내 함수 내에서 사용하면 효과가 있습니다. OP가 이것을 확인할 수 있습니까? 함수 내에서 echo하는 경우 실제로'href = "example.com"'을 출력합니까? – BeetleJuice

답변

0

사용 :

public function myFunction() 
{ 
    //... 
    // example data 
    $data = array(
     'url' => 'example.com', 
     'value' => 'Go to website!' 
    ); 

    $htmlPart = "<a href='".$data['url']."'>".$data['value']."</a>"; // change to this 

    $html = // rendered $htmlPart with variables 

    return $html; 
} 
+0

그는 문자 그대로 * 그의 데이터베이스에 저장된 문자열'{$ data [ 'url']}'을 가지고 있다고 생각합니다. –

0

당신은 문자열에서 변수를 구문 분석하고 그 값으로 대체하기 위해 정규식과 preg_replace_callback를 사용하여 시도 할 수 있습니다. 이 같은

뭔가 :

<?php  
$data = array(
    'url' => 'example.com', 
    'value' => 'Go to website!' 
); 

//Here I get html code from database, let's say it looks like this: 
// Single quotes so it's the *literal* text 
$htmlPart = '<a href=\'{$data[\'url\']}\'>{$data[\'value\']}</a>'; 

// Double backslashes needed so the regex is correct 
$html = preg_replace_callback("/\\{\\$(.*?)\\['(.*?)']}/", function($matches) use($data){ 
    return $data[$matches[2]]; 
}, $htmlPart); 

echo $html; 

DEMO : https://eval.in/607169

관련 문제