Replace a string with HTML - php

I'm using str_replace as follows:
<html>
<head>
</head>
<body>
<script type="text/php">
$new_str = str_replace( '[[str_to_replace]]' , $GLOBALS['html'] , $original_str );
</script>
<div class="wrapper">[[str_to_replace]]</div>
<?php
// multiple includes
// lots and lots of code
//PHP code to calculate HTML code
//value of $html depends on data calculated after div.wrapper is drawn
$GLOBALS['html'] = '<input type="text" />';
?>
</body>
</html>
I'm forced to wrap the PHP code in a script tag because the document is getting passed to a library as an HTML document. The library has the ability to execute PHP code inside script tags but in this case is working oddly.
What I'm expecting:
[[str_to_replace]] should become an HTML input field.
What I'm getting:
[[str_to_replace]] becomes the literal string <input type="text" />.
How do I get the second result?

You're likely misinterpreting wht you can do with inline script. In dompdf HTML is parsed separately from inline script. Any HTML you insert into the document using inline script will be treated as plain text. What you should be doing is parsing your document first then passing the results to dompdf.
FYI, It's hard to see from your sample exactly what you're doing in the code. Plus we can't see what's going on with dompdf. I'm having a hard time seeing how everything ties together.

It sounds like what you're trying to do is to replace the string with decoded HTML entities. You'll probably want to do:
$htmlEntityString = '&'; // String containing HTML entities that you want to decode.
$new_str = str_replace( '[[str_to_replace]]' , html_entity_decode($htmlEntityString) , $original_str );
In this case, whatever HTML you have with HTML entity form will be decoded and will replace the substring.
Read more about it for all the options:
http://php.net/manual/en/function.html-entity-decode.php

Related

HTML string from API not being converted to HTML rendered entities

I'm receiving a chunk of HTML via API call and trying to put that HTML into my template for it to render. But, instead of rendering, it's being printed out as if it were a string.
Example of HTML string from API:
\u0026lt;p\u0026gt;\u0026lt;strong\u0026gt;Hello World\u0026lt;/strong\u0026gt;\u0026lt;/p\u0026gt;
Then in the controller I convert the string to HTML entities
$content = htmlspecialchars_decode($response['content']);
The issue I'm having is that in my view, the HTML is printed (tags and all) instead of being rendered as HTML:
In view code:
<?= $content ?>
End result:
<p><strong>Hello World</strong></p>
How can I get this HTML chunk to render in my view?
Your data looks like double-encoded. Try
$content = htmlspecialchars_decode(htmlspecialchars_decode($response['content']));
From the looks of your string, you don't need htmlspecialchars_decode(), since you don't have HTML special characters directly in it.
I suspect you are getting your data in JSON format. A JSON-encoded value can sometimes have special characters converted to Unicode constants (for example, the PHP json_encode() function does that when used with the JSON_HEX_* options).
Try this:
$content = json_decode('"' . $response['content'] . '"');

Prevent php from rendering/executing between pre tags

I'm using pre tags to display codesnippets on my website, these snippets contain html and php.
So far I've used Jquery to convert html in the codesnippets to plain text, but the php tags are still being executed.
The code that I used for converting the html contents of the pre tag to plain text:
$(document).ready(function(){
$("pre").text($("pre").html());
});
An example of what I'm using it on:
<pre>
<p>paragraph Content</p>
<h1>html code</h1>
<?php echo "this is php example code"; ?>
</pre>
The first 2 lines display in the browser with the tags and everything perfectly, but the third line execute the php tags rendering only this php example code. Can anyone help me out so I can display the php tags in my code snippet aswell?
Also if anybody knows a better solution to rendering html/css and php as a code snippet on your website It would be really helpfull.
The problem with your approach is, that you try to influence the rendering after the browser has processed the file. When you look at the sourcecode of your page, you will notice that there really is nothing else than "this php example code" in there, because the server parsed that part of your code and executed it, which leads to nothing but the string you put into that echo command.
You need to handle your output before your send it to the client and fetch all occurrences of <pre> and </pre> to replace all < and > between them with their respective HTML entities.
Have a look at this question to find out the best approach to parse the HTML and get the appropriate elements in order to modify them.
You should escape the < and > symbols - replace them with their HTML entities, < and > respectively ;)
If you want a total and comprehensive conversion to HTML entities, try converting them over at http://centricle.com/tools/html-entities
Generally it's good practice to convert all symbols to their respective HTML entities within a code block.
Try to replace <?php ... ?> with
<? .... >
<pre>
<p>paragraph Content</p>
<h1>html code</h1>
<?php echo "this is php example code"; ?>
</pre>
Here's a JSFiddle example so you can see how it renders on the page.

Encoding and decoding with php and javascript and data attributes validation

Im using data-attributes for sending data from html to javascript
The data attributes come from mysql data so it might have a space in it, so
i get validation errors as it says no space are allowed inside attributes
So the solution i thought if is to encode the value in php so it has no spaces
and then decode it in javascript once it has been passed on to javascript. Is there a premade function for this?
A failsafe way will be awesome :)
Also is there a way to store values in data-attributes with having space in it and getting it to validate?
spaces in html attributes shouldn't be a problem (just think of the style attribute: style="background-color: #F63;" has a space in it, but will still work. If the data is sent using ajax however,chances are it gets url encoded (#Brad: urlencode is what you meant, I suspect).
since you say the data is coming from an SQL table, chances are the data itself is passed is stored in either an object or an array in php. If so, why not just json_encode the data, and in javascript: JSON.parse(document.getElementById('theId').value);. This gives you an object in JS, containing all data you have. If only 1 string is required, you can sill use json_encode by placing your data in a wrapper array, and encode that...
Do make sure to use SINGLE quotes if you string this to html:
<?php
$dbArray = array('this', 'array', 'contains','your','data', 'with spaces');
$html= '<input type="hidden" id="hiddenArray" value=\''.json_encode($dbArray).'\'/>';
If you use single quotes the element will be malformed, since json encoded arrays have double quotes in them:
<input type="hidden" id="hiddenArray" value='["this","array","contains","your","data","with spaces"]' />
Might not look sexy, but as you can see, double quotes would have set the elements value to [...
This doesn't strip spaces, but they won't cause you any problems either.
Also is there a way to store values in data-attributes with having space in it and getting it to validate?
Just make sure you quote your attribute values.
This is a valid document that passes at the W3C validator.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Data Attributes</title>
</head>
<body>
<h1 data-space="This value has a space in it">Data Attributes</h1>
</body>
</html>
If you html encode them in PHP using something like htmlentities you can then decode them in javascript using unescape
<?php
$value = htmlentities('hey you'); //hey%20you
and then in javascript
var value = unescape('hey%20you'); //hey you

Displaying HTML code

How can stop HTML code from rendering and display it as standard text, so my users can simply copy and paste it for their own usage?
You could use the function htmlentities(). Have a look at the manual.
Please note that by default the data will be returned using the ISO-8859-1 character set. You might want to change the third parameter to UTF-8.
For example:
$html = "<div>Some text</div>";
echo htmlentities($html);
Use PHP to set the content type:
header("Content-Type: text/plain");
You parse it into markup which uses HTML entities, for example instead of using:
<body>
you would instead use entity codes to escape the markup characters, like this:
<body>
There are plenty of references to be found which list entity codes, and it's pretty easy to parse and escape HTML in most programming languages.
HTML code can be displayed using php script by using functions htmlentities() and htmlspecialchars(). For understanding this concept consider the following example:
<?php
$a="<h1>heading tag: used for heading tags</h1>";
echo htmlentities($a)."<br/>";
echo htmlspecialchars($a);
?>
Output will be:
<h1>heading tag: used for heading tags</h1>
<h1>heading tag: used for heading tags</h1>

PHP MySql display returned content without html tags being stripped

I have a column in SQL 'Text' datatype and inside I have content within html tag, eg somecontent: onetwo... I want the mysql query to echo out the databases contents without stripping the html tags (its possible this is done by php for security reasons or?) so that the html code will render if you get me? At the moment it just lumps out a paragraph which looks aweful! It should be noted security is not much of a concern as this is a project and not going to be exposed publicly
Cheers folks
Nick
MySQL wouldn't strip tags from text - it couldn't care less what the text is. PHP also wouldn't strip tags, unless somewhere in your code you do a strip_tags() or equivalent.
If you want to force the browser to display the tags in the retrieved data, you can run the string through [htmlspecialchars()][1], which converts html metacharacters (<, >, ", &, etc...) to their character entity equivalents (<, >, etc...).
Or you can force the entire page to be rendered as plain text by doing
header('Content-type: text/plain');
Database content isn't stripped by PHP unless you explicitly tell it to.
Are you sure your tags haven't been stripped before they were inserted?
Alternatively try stripslashes();
Use htmlspecialchars_decode() function. Its works fine for me...
Use guideline
Your Text with code
<?php
$text = "
<html>
<head>
<title>Page Title</title>
</head>
<body>
Reference site about Lorem Ipsum, giving information on its origins, as well as a random Lipsum generator.
</body>
</html> ";
OR
$text = $row['columnname']; // Here define your database table column name.
echo htmlspecialchars_decode($text);
?>
Output:
Reference site about Lorem Ipsum, giving information on its origins, as well as a random Lipsum generator.
this works for me:
Ex:
<?=htmlspecialchars_decode(htmlspecialchars('I <b>love</b> you'))?>
Your browser will output:
I love you
Use bellow snippet:
echo(strip_tags($your_string));
copied.

Categories