cadi2108
cadi2108

Reputation: 1280

php code inside variable with html code

I want to add code php to variable with html, for example

$html = '<b></b> <?php echo $lang["text"] ?>';

but it don't interpret php code. What am I doing wrong?

Upvotes: 3

Views: 3391

Answers (6)

cheskapac
cheskapac

Reputation: 51

make sure file extension is php.

<?php
     $html = '<b>' . $lang["text"] . '</b>';
?>

Upvotes: -5

Mouloud
Mouloud

Reputation: 3795

its very important to escape the output. (security basics)

$html = sprintf('<b>%s</b>', htmlspecialchars($lang['text']));

Upvotes: 3

ase
ase

Reputation: 13461

What you want is called string interpolation (read about how it works for PHP).

Your particular example would be solved using

$html = "<b></b> {$lang['text']}";

String interpolation only happens in double quoted string ("string here").

Upvotes: 5

c0deMaster
c0deMaster

Reputation: 76

Use string concatenations like this:

$html = '<b></b>' . $lang['text'];

or insert variable in double quoted string like this:

$html = "<b></b>${lang['text']}";

both versions are correct, use the one that you like.

Upvotes: 6

Quentin
Quentin

Reputation: 943108

You can't switch from "Output raw text mode" to "Run PHP code mode" in the middle of a string while you are already in "Run PHP code mode"

$html = "<b></b> ${lang['text']}";

… although why you want an empty bold element is beyond me.

Upvotes: 2

Sherlock
Sherlock

Reputation: 7597

<?php

$html = '<b>'.$lang['text'].'</b>';

?>

Upvotes: 2

Related Questions