Find and replace <?php & ?> in string - javascript

I have a large string of valid HTML code that will be inserted into the DOM, the string also contains PHP code. I want the php code to be displayed as plain text, Chrome automatically comments out the PHP code. Obviously the PHP code is wrapped in <?php ... ?> so my question is:
How can I replace the open <?php with a <span> tag, and replace the ?> with a </span> to close the open <span> tag so that the PHP code is within the <span> tags and therefor visible as plain text?
EDIT: I will be wrapping the PHP code back in <?php ?> by replacing the span, so escaping the characters will make that more difficult.

You could escape it.
From:
https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

As you say that the HTML is a string, you can easily just use the replace() function.
var html = // your html
var sanitized = html.replace(/<\?php/g, "<span>").replace(/\?>/g, "</span>");

Use Regular Expressions!
RegExp101 is a great playground.
Remember to change the flavor on the left menu to JavaScript.
The easiest way is using the .replace() function.
var str = str.replace(/(<\?php)|(<\?)|(<\?=)/g, '<span>').replace(/(\?>)/g, '</span>');
Edit: As requested by Get Off My Lawn, I've added support to <?= nd <? tags. The pipe | represents an or in Regular Expressions.

Related

Javascript not working inside a PHP function

I'm new to javascript.
There seems to be no result but a blank screen when I try the following code:
function send_to_class($data)
{
echo 'PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP';
?>
<script type="text/javascript">
$(".username").append(<?php echo $data;?>);
</script>
<?php
echo 'EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE';
}
and my PHP
$data = "You might think I'm Bonkers, but I just think I'm Free";
send_to_class($data);
and my html
<span class="username"></span>
The Function is declared before the send_to_class($data) is initiated.
The P's and the E's are showing up just fine, there's just no middle sentence.
I've tried divs, id's and classes, adding css and changing the script tag.
2 things, a) how do I get the function to work which appends $data to the .username class and b) how do I get it to work if $data is an array? Can Javascript print php arrays in this manner?
Thanks.
I found that because the $data I was sending contained "'s that it needed to have the "'s escaped. So in my php file that was producing the data, I had to turn the following:
<div class="class1">some words</div>
into this:
<div class=\"class1\">some words</div>
This is because it's javascript that's doing the printing, and when javascript does printing of "'s it needs to have them escaped with a backslash like this \".

how to display double quote instead of &34; from php variable

I am pulling my hair with this simple task...
From a php variable that contains double quotes (") which is echoed in a div, the html source shows that " have been replaced by ". So far OK.
However, when the html code within the div is copied with jQuery, some of the double quotes are repeated.
I need to fix that in order to use MindMup editor properly.
$Text = 'This is an <span class="myclass">example</span> where double-quotes are added by "I don\'t know what".'
<a onclick="javascript:copyEditor();">copy code</a>
<div id="editor">
echo $Text;
</div>
<script>
function copyEditor() {
$('#hiddenEditor').html($('#editor').html());
}
</script>
If the text is typed directly into the html page with double quotes, then it is fine. See the difference in that example.
So my question is how do I stop php/html to convert the double quotes into " when displaying that variable in the page?
There is also an empty line added on top in the link above after copying the code... why?
Replace double quotes with "
To replace the quotes in user input:
$escaped_quotes = str_replace( "\"", """, $string );
source

Updating innerHTML property of a tag in PHP

I am trying to update innerHTML property of paragraph tag in PHP. I made a rest API call that gets the date and after parsing it. I am adding the result(HTML table constructed by parsing the results from API) to a <P> tag already in page. I am using following PHP code to do so:
$dom = new DOMDocument();
$child = $dom->createElement('p',$myresult);
$dom->appendChild($child);
$dom->SaveHTML();
$myresult is the string that contain html table with information. The above lines are executed smoothly but no change in p tag content.
I tried this too, but no change in output:
<?php echo "<script>document.getElementByID("#id").innerHTML = ". $myresult."</script>"
Am I doing anything wrong?
try this
<?php echo "<script>document.getElementByID(\"id\").innerHTML = ". $myresult."</script>" ?>
you need escaping quotation on getElementByID and u dont need #
You should escape double quotes inside a double-quote string in PHP. But, you can as well use single quotes instead like so:
<?php echo "<script> document.getElementById('id').innerHTML = '$myresult' </script>"; ?>
Also, it is getElementById not getElementByID. And remove the # from getElementById().
Try:
<?php echo "<script>document.getElementById(\"id\").innerHTML=".$myresult."</script>" ?>
as long as id is an existing html element id and $myresult is a php variable containing html
OR
You may try
<div id="id"><?php echo $myresult; ?></div>
Notes:
1. It is getElementById() not getElementByID()
2. Usually #id is used in jquery, and in pure JS it is just id

Change href in div to normal text

I have one problem. On my website, I have <div id="alpha_bravo">, with links inside. It looks like this:
<div id="alpha_bravo">
<p>text text text link</p>
</div>
I want change every <a href...> to funny text like suprise, as an example.
How can I do it?
Since you tagged the question with PHP and from the comments below the question it seems that you may want to use server-side functionality, I'm going to give an example using PHP.
One way is to replace only links. You are looking for preg_replace() function that will replace all substrings in the string based on a regex pattern.
$input = "<div id='alpha_bravo'><p>text text text <a href='...'>link</a> and <a href='...'>another link</a></p></div>";
$output = preg_replace("/<a (.*?)>(.*?)<\/a>/i", "surprise", $input);
You can also just remove all HTML tags in the string using strip_tags() function.
$input = "<div id='alpha_bravo'><p>text text text <a href='...'>link</a> and <a href='...'>another link</a></p></div>";
$output = strip_tags($input);
Given that this is coming from a database, first word of advice is that you filter your input before saving it in database.
Secondly, if you don't want those links to render and replace them with some other value then use PHP's function preg_replace() as already mentioned by PetrHejda..
PHP docs: http://php.net/manual/en/function.preg-replace.php
Your <a ...>...</a> pattern may differ if users insert styling and classes.
Try using this pattern as your solution: preg_replace("/<a(.+?)href=\"(.+?)\"/", "<a$1href=\"your_value_here\"", $yourStringHere);
You may use g or i flags. Start here with regular expressions: http://www.regular-expressions.info/.

Apostrophes issu with php and jscript

I have this piece of code, which doesn't work, I couldn't find where is the problem?
$texttt = "blabla";
echo "<div onclick='select(\" page d \' accueil \");'>".$texttt."</div><br/>";
function select(text){
alert(text);
}
" is breaking your php statement
echo "<div onclick=\"select(' page d\' accueil ');\">\"Page d'accueil\"</div><br/>";
function select(text){
alert(text);
}
try to use addslashes and htmlentities to escape the quotes between text
$texttt = htmlentities(addslashes($text), ENT_QUOTES);
echo "<div onclick='select(\"$texttt\");'>$texttt</div><br/>";
Use single quotes for PHP. I use single quotes for PHP (which is server side script) and double quotes for client side scripts unless it is not obligatory.
echo '<div onclick="select(\'page d\'accueil\');">"Page d\'accueil"</div><br/>';
the problem is sourced by single quote in d'accueil:
I dont know if it is possible to escape a string which is located in another escaped string.
The possibilities:
You can change the grammar rules of your language:
Affects too many people.
Not applicable.
You can change the way of typing single quote: using ' in context.
I have typed a new code (which is working well) for you :
<?php
echo '<div onclick="select(this.innerHTML);">"Page d'accueil"</div><br/>';
?>
<script>
function select(text){
alert(text);
}
</script>
you should avoid useless quotes before you get lost inside.
"Page d'accueil" don't need to be between quotes so remove them.
Use one kind (single or double quotes) for the first level of quoting, and the other for the next levels, and keep that it mind.
<? php echo '<div onclick="select(\" page d\' accueil \");">Page d\'accueil</div><br/>'; ?>
<script type="text/javascript">
function select(text){
alert(text);
}
</script>
you can use heredoc syntax
refreence : http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
also try this:
echo json_encode("<div onclick='select(" page d ' accueil ");'>{$texttt}</div><br/>");

Categories

Resources