So I have this practical page I made to see if I can make a template language, the code is listed below:
JavaScript
x
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function get_attributes($element) {
$output = explode(" ", $element);
return $output;
}
function build_element($item, $attributes) {
switch($element) {
case "form";
$template = "<form {{attributes}}>";
$template = str_replace("{{attributes}}", $attributes, $template);
return $template;
break;
}
}
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$fullstring = '
<xe:form style="width:100px; height: 100px; background: #55ff55;"></xe:form>
';
$parsed = get_string_between($fullstring, '<xe:', '>');
$e = get_attributes($parsed);
$full = '<{{et}} {{attr}}></form>';
$full = str_replace('{{attr}}', $e[1], $full);
// the str_replace() bellow this comment is causing issues
$full = str_replace('{{et}}', $e[0], $full); // <--------------------- issue is here
echo $full;
It seems like if I add 2 str_replace
functions, the echo
is blank, and the $e
var is working fine.
I tried echoing out both $e
vars, but they are both fine.
If someone could point me in the right direction, I’d greatly appreciate it.
Advertisement
Answer
The result is:
<form style=”width:100px;></form>
Not sure what do you want exactly, but:
- the style attribute is opened with a double quote, but not closed, causing the form to be not visible.
- you didn’t parse the attributes perfectly as you miss the height and bgcolor. (separating with the space is not a good idea as some attributes can have space in the value)
HTML is fair complex, you might want to check out https://www.php.net/manual/en/class.domdocument.php to manipulate it without weird issues. You may change a few things with search&replace, but they will break easily.