remove and add character from string - php

I would like to replace \n with a new line.
This is the result from database:
<!DOCTYPE html>\n<html>\n<body>\n<div>\n<label class=\"s20 c03\">Label</label>\n</div>\n</body>\n</html>
I want the string to be aesthetically pleasing, for example:
<!DOCTYPE html>
<html>
<body>
<div>
<label class="s20 c03">Label</label>
</div>
</body>
</html>

It sounds like the \n are burnt into the string. To replace them with actual newline characters, use this:
$replaced = preg_replace('/\\\\n/', '\n', $yourstring);

You should definitely find the source of the double escaping first.
To undo your very exact data issue, there is stripcslashes() however.
Replaces a literal \n with a newline.
And the \" into a plain double quote.
It also undoes \r and octal \000 or hex \x00 escapes, or (it's most likely that your database also contains these) the double backslash \\ back into a singular one.

#ahmadalbayati is on the right track I think.
Pretty Markup
If you just want the database-returned string to look pretty in the returned page's markup (i.e. via View Page Source in a browser), simply echo it where you want it in the markup...
<?php
$dbResponse = "<!DOCTYPE html>\n<html>\n<body>\n<div>\n<label class=\"s20 c03\">Label</label>\n</div>\n</body>\n</html>";
echo $dbResponse;
?>
...which yields the following markup:
<!DOCTYPE html>
<html>
<body>
<div>
<label class="s20 c03">Label</label>
</div>
</body>
</html>
Pretty Rendered Page (and Markup)
If you want to show the database-returned string when the returned page is rendered, you can use the str_replace and htmlspecialchars functions in conjunction as follows...
<?php
$dbResponse = "<!DOCTYPE html>\n<html>\n<body>\n<div>\n<label class=\"s20 c03\">Label</label>\n</div>\n</body>\n</html>";
echo str_replace("\n", "<br />\n", htmlspecialchars($dbResponse));
?>
..., which yields the following displayed page...
<!DOCTYPE html>
<html>
<body>
<div>
<label class="s20 c03">Label</label>
</div>
</body>
</html>
...and the following markup behind it:
<!DOCTYPE html><br />
<html><br />
<body><br />
<div><br />
<label class="s20 c03">Label</label><br />
</div><br />
</body><br />
</html>

Related

TinyMCE angle brackets

I am new to using TinyMCE but am frustrated with its behavior of angle brackets. It appears to be interpreting input such as <foo> or <foo>Foo</foo> as tags despite the page source showing that both cases are converted to <foo> and <foo>Foo</foo> respectively
I reduced my code for SO, it is below:
<?php
// Simplified for SO, no file writing / reading
$content = isset($_POST["forSo"]) ? $_POST["forSo"] : "";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>For Stack Overflow</title>
<script src="/tinymce/js/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({ selector : "#forSo" });
</script>
</head>
<body>
<?php
// Behaves as expected, TinyMCE correctly automatically converts HTML Entities
echo $content . "\n";
?>
<form action="/forSo.php" method="post" enctype="multipart/form-data">
<textarea id="forSo" name="forSo">
<?php
// Page source shows that this has HTML Entities, still loses information
echo $content . "\n";
?>
</textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
If I input say <foo> then the resulting page source is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>For Stack Overflow</title>
<script src="/tinymce/js/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({ selector : "#forSo" });
</script>
</head>
<body>
<p> <foo></p>
<form action="/forSo.php" method="post" enctype="multipart/form-data">
<textarea id="forSo" name="forSo">
<p> <foo></p>
</textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
However TinyMCE seems to have thrown away the textarea's content resulting in this (hitting submit again causes all of $content to be an empty string):
Replacing the second <?php echo $content . "\n"; ?> inside the textarea with <?php echo str_replace("&", "&", $content) . "\n"; ?> accomplishes the task
This does prevent writing valid HTML tags but text that is meant to be taken literally such as <foo> is preserved inside the TinyMCE editor as &lt;foo&gt; as opposed to <foo> which TinyMCE interprets as a HTML tag

PHP code is not being interpreted

I am writing a code that contains HTML as well as PHP commands. When I try to run the code on my browser, I get this message :
Parse error: syntax error, unexpected $end in C:\WAMP\www\urr00001\SummerProject\projectquestionnaire.php on line 21.
I don't understand why line 21 is wrong. I was under the assumption that the "echo <<<_END ... _END" construct must be used whenever multiline HTML must be output. But the browser does not like this. My code is shown below. How can I correct this situation, please?
<?php //questionnaire.php
if (isset($_POST['name'])) $name = $_POST['name'];
else $name = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Questionnaire</title>
</head>
<body>
Your name is: $name<br>
<form method="post" action="questionnaire.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
It's confirmed, you do have spaces before _END; (remove them)
Use this: (exactly as posted)
<?php //questionnaire.php
if (isset($_POST['name'])) $name = $_POST['name'];
else $name = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Questionnaire</title>
</head>
<body>
Your name is: $name<br>
<form method="post" action="questionnaire.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
Consult heredoc syntax
Warning
It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.
Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.
Allowed: (no spaces)
</html>
_END;
?>
Not allowed: (1 or more spaces)
</html>
_END;
^--// that's a space, and you have many.
?>
This is just an opinion, but I would much rather see this in the code:
**<?php //questionnaire.php
if (isset($_POST['name'])) $name = $_POST['name'];
else $name = "(Not entered)";
?>**
<html>
<head>
<title>Questionnaire</title>
</head>
<body>
Your name is: **<?php echo $name;?>**<br>
<form method="post" action="questionnaire.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
Because it lets others know (especially those who know HTML but not PHP) exactly where PHP is used and where the file is only HTML and let's them see it at a glance. Your file would still be named .php, by the way. Of course, if your project is requiring "echo <<<_END..._END;" then you have to use that.

How to stop HTML text in textarea to be interpreted as code

I have a textarea that users can edit. After the edit I save the text in a PHP variable $bio. When I want to display it I do this:
<?php
$bio = nl2br($bio);
echo $bio;
?>
But if a user for example types an HTML command like "strong" in their text my site will actually output the text as bold. Which is nothing I want.
How can I print/echo the $bio on the screen just as text and not as HTML code?
Thanks in advance!
Replace echo $bio; with echo htmlspecialchars($bio);
http://php.net/htmlspecialchars
When you output text to the html / the browser and you want to make sure that the output does not break the html, you should always use htmlspecialchars().
In your case you do want to show the <br> tags, so you should do that before you add them:
$bio = nl2br(htmlspecialchars($bio));
You can also use strip_tags() to get rid of the html tags altogether, but you would still need to use htmlspecialchars() so that for example a < character will not break your html.
You can also use htmlentites()
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body>
<form method="POST" action="">
<p><textarea rows="8" name="bio" cols="40"></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
<p>Result:</p>
<?php echo isset($_POST['bio']) ? htmlentities($_POST['bio']) : null; ?>
</body>
</html>
So like:

How to read data from a html text box, and print(echo) the data in php in the same format as in the text box?

I am beginner to PHP and here is my question.
I have a text box and a 'Print' button. If 'Print' button is clicked, it should display the list of names entered in the text box. I'd written the following code, but the problem is, if I click the 'Print' button, it shows the names in a single line, instead of showing names in line by line format. Can someone help me in this. Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Form Page</title>
</head>
<body>
<form action="Files.php" method="get">
<textarea rows="15" cols="30" value="textbox" name="textbox"></textarea></br>
<input type="submit" value="Print" name="Print">
</form>
</body>
</html>
<?php
if(isset($_GET['Print'])){
$file_print = $_GET["textbox"];
echo $file_print;
}
?>
You need to use nl2br() in PHP
Replace echo $file_print; with echo nl2br($file_print);
For edit..
echo nl2br($file_print);
file_put_contents('names.txt',$file_print,FILE_APPEND); //<-- Remove FILE_APPEND if you want to overwrite the file
Use nl2br()
nl2br — Inserts HTML line breaks before all newlines in a string.
So in your case, you need to do this echo nl2br($file_print);

PHP - GET Method adds unnecessary additions symbols to URL

I looked around Stack Overflow for the recommended method type for PHP; either the GET or POST method. Recommended by the community, the GET method seems to be a good idea for passing queries for a simple search engine.
Unfortunately, the GET method adds unnecessary addition symbols to the URL to indicate spaces. Basically, a aesthetic issue.
I tried the trim() function to lessen the spaces, however, that is only called after the data is submitted and the URL is already set with the parameters.
Here is a the index.php file I think is not cooperating with me.
<?php $query = ""; ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="index.php" method="GET">
<input type="text" name="query" placeholder="Enter Query">
<input type="submit" text="Search">
</form>
<?php
$query = $_GET['query'];
print $query;
?>
</body>
</html>
A example, if needed. If I type into the search bar this query...
sample 1
The URL will be formed this way...
http://localhost/search/index.php?query=sample++++++++++++++1
Is there a way to fix this problem or is the POST method the only way to circumvent this problem?
You will need to use the POST method.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="index.php" method="POST">
<input type="text" name="query" placeholder="Enter Query">
<input type="submit" text="Search">
</form>
<?php
$query = $_GET['query'];
print $query;
?>
</body>
</html>
Use urlencode or str_replace.
urlencode will replace all spaces with plus symbols, and with str_replace you can replace either underscores with plus symbols, or spaces with minus symbols.
Replace spaces with underscores: str_replace(' ', '_', $url);
Urlencode your $_GET*: urlencode($url);

Categories