Использование str_replace для замены комментариев HTML тегами PHP

Используя PHP, я пытаюсь создать функцию, которая заменит определенные открывающие и закрывающие комментарии HTML открывающими и закрывающими тегами PHP.
Когда я вношу закомментированный HTML в качестве строки темы, он внедряется в документ HTML, а не заменяется тегами PHP. Однако, когда я ввожу что-то кроме комментариев HTML, это нормально — как и следовало ожидать.
var_dump () возвращает string (32) «» и NULL для $ foo и $ bar соответственно.
Например, функция ниже предназначена для замены:

    <!--CODE echo"hello world"; CODE--!>

С:

    <?php echo"hello world"; ?>

Код:

    <?php
function code($subject){
$php=array("<?php","?>"); //the replace string array
$html=array("<!--CODE","CODE--!>"); //the search string array
$subject=str_replace($html,$php,$subject); //search the subject and replace strings
}
if(isset($_POST['submit'])){
$foo=$_POST['foo'];
$bar=code($foo);
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
var_dump($foo);
var_dump($bar);
?>
<form method="post" action="">
<input type="text" name="foo" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Есть идеи? Был бы признателен за ваш вклад.

1

Решение

Я надеюсь, что это то, что вы пытались достичь.

<?php
function code($subject) {
$php = array("<?php", "?>"); //the replace string array
$html = array("<!--CODE", "CODE-->"); //the search string array
return str_replace($html, $php, $subject); //search the subject and replace strings
}

if(isset($_POST['foo'])) {
$foo = $_POST['foo'];
$bar = code($foo);
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<?php
if (isset($foo)) {
echo 'foo = ';
var_dump($foo);
}

if (isset($bar)) {
echo 'bar = ';
var_dump($bar);
}
?>

<form method="post" action="">
<input type="text" name="foo" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Я отредактировал закрывающий тобой комментарий $html массив со стандартным закрывающим тегом комментария HTML и отредактировал третью строку вашего code() функция. Теперь значения не назначены обратно $subject но восстанавливается (return str_replace($html, $php, $subject)).

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector