Line Breaks When Using PHP to Write a Javascript Alert [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)
I am using javascript to do some form validation on a php page. There are several parts to it, but a typical one looks like this:
var brek=document.forms["seasonprice"]["price_brek"].value
if (brek==0)
{
alert("<?php echo $lang["brekzero"] ?>");
return true;
}
$lang['brekzero'] is defined in an included language file. As the text is fairly long I want to break it up onto several lines for better readability. I expected to be able to do that by inserting \n in the appropriate places. Instead it stops the alert working altogether, and it took me a long time to identify that as the cause.
What should I be doing instead?
The same script has also been giving me problems with accented letters. Writing á in the lang file results in á appearing in the alert instead of á. Writing á in the lang file causes strange symbol to appear in the alert. For the moment I've taken the very English way out, and left out the accents!

You need escaped \n characters:
echo str_replace("\n", "\\n", $lang["brekzero"]);

Related

How to write HTML code inside PHP [duplicate]

This question already has answers here:
Is there a better way to write HTML strings in PHP?
(8 answers)
Closed 8 years ago.
My PHP code begins with the ?php tag and ends with the ? tag and my file extension is php. If I want to write part of my PHP code inside HTML, what is the general way of doing it?
For instance:
echo '<strong>' .$element .'</strong><br>';
Do I need to always use single quotes for the HTML tags used inside of a PHP file? Or double quotes or no quotes?
The first thing you need to learn is that PHP doesn't care about HTML.
PHP doesn't understand that it's working with HTML, it just sees text and dutifully sends it to the browser. The browser then makes sense of it as HTML.
So, since <strong> is a string, it must be treated as a string. In other words, as "<strong>", '<strong>' or even a heredoc:
<<<HEREDOC
<strong>
HEREDOC;
(Probably not appropriate in this case :p)

PHP - Unable to remove whitespace from string [duplicate]

This question already has answers here:
Trim whitespace ASCII character "194" from string
(7 answers)
Closed 6 months ago.
I have a piece of code that reads in values from a CSV file, all working grand and then each individual record is validated and used in an API call to an external source, all of this is working grand.
Now today I have a CSV file uploaded that when I open it it looks to have 3 spaces at the end of each entry in the CSV which causes the API call to fail.
I've tried using trim() but it doesn't do anything, I've also tried using preg_replace('/^((?=^)(\s*))|((\s*)(?>$))/si', '', $pValue) and this isn't having any affect either.
I opened the CSV file in Notepad++ and enabled it to show all symbols, there are clearly 3 spaces and the CR and LF.
Has anyone come across an issue like this before, code snippets below and an example on codepad.
EDIT:
Example: http://codepad.org/DfjzPcUU
Code snippets, if more is needed please let me know.
$vCSVData = self::getCSVData($vPendingFilePath);
foreach ($vCSVData AS $vKey => $vValue)
{
echo self::getNubmer($vValue);
...
}
getCSVData():
private function getCSVData($pFilePath)
{
return call_user_func_array('array_merge', array_map('str_getcsv', file($pFilePath, FILE_SKIP_EMPTY_LINES)));
}
CSV File Snippet:
Blue Table   
Green Chair  
Temp. Table   
As it turns out that what I thought was white space was actually ASCII 194 characters (Thanks to MikeB) for figuring this out, as trim, rtrim, preg_replace, str_replace with the normal " " (empty space) check didn't work the below snippet is what worked for me.
preg_replace("/[\xA0\xC2]/", "", "Table ")
xA0 is char 160 and xC2 is char 194.
Also you can use trim in this instance by using the below statement, using trim over preg_replace is slightly faster for processing time, with that said the overheads in each case and the difference are negligible, in my case either will suffice.
trim("Table ", "\xA0\xC2")
Example: http://codepad.org/8H5Ut2KA
I was able to find out what the 'space' was by using the below code snippet:
var_dump(ord($vString{5}));

PHP wont show new line [duplicate]

This question already has answers here:
Echo from MySQL database with spaces and line breaks?
(2 answers)
Closed 9 years ago.
i have a little problem with the text to be readed from my database.
After the user has confirmed their new post, it saves in the database like this ( like i want it to do).
but in the webpage, it will ignore these lines, and just echo out everything on the same line.
Here is a bit my source code:
$objekttekst=str_replace("\\r\\n", "<br>", $obj->innhold);
$objekttittel=$obj->tittel;
?>
<h2><?=$objekttittel?></h2>
<p><?=$objekttekst?></p>
could someone help me out? thanks
Use nl2br() function.
$objekttekst = nl2br($obj->innhold);
The input textarea is pre-formatted, which means that it will show any newlines that the user enters. However, HTML rendered (web browser) does not display any newlines from the input, unless newlines are explicitly inserted with tags such as <BR>.
You have several options here. For sure these three are not your only options, but they are the ones I have personally been using most often.
Form textarea with pre-formatted text
If you want to display the data (objekttekst) in a similar textarea where the input was given, you could do:
<h2><?=$objekttittel?></h2>
<p><textarea><?=$objekttekst?></textarea></p>
This would suit you best in a situation where the user needs a possibility to edit the entry.
Preformatting
If you want to display the text as it is, you can always surround it with <PRE>...</PRE>. That will show any newlines, indentations etc. Note that this will make the output use a fixed-width font such as Courier New.
Convert newlines to <BR> tags
Use function nl2br() as already mentioned in another answer. See: http://php.net/manual/en/function.nl2br.php for more information.
Additional note...
You might want to look into regular expressions, as in many cases you might want to do also some other modifications to your data before showing it in the HTML page. nl2br() will take care of newlines, but for other and more complex modifications you should learn regular expressions.
You can surround your string with <pre> tag instead of replacing \n with <br>
Example:
<?php
$objekttekst=$obj->innhold
$objekttittel=$obj->tittel;
?>
<h2><?=$objekttittel?></h2>
<p><pre><?=$objekttekst?></pre></p>

PHP how to include everything i type in my textbox to mysql database [duplicate]

This question already has answers here:
How do I escape special characters in MySQL?
(8 answers)
Closed 8 years ago.
i was wondering how can i include everything written on my textbox to be inserted in mysql database
for example:
textbox = "{\buildrel{\lim}"
but what happens is the \ (backslash) remove 'b' and 'l' and the data inserted to my database will be
{uildrelim} somewhat like this, it might come up removing the { } as well
so is there any techniques or method you can advise? so that everything i put in my textbox will be inserted to my database as it is.
I found this solution:
i just need to use the str_replace() method to replace single \ with double \\
$textbox = str_replace('\\\','\\\\\\\',$textbox);
where {\buildrel{\lim} will be {\\\buildrel{\\\lim}
No, You dont use str_replace(), you have addslashes() and stripslashes(), those two are the two functions you are looking for.
Changing a string with str_replace functions isnt a smart thing to do. Those functions aren't created with this in mind, the add/striposlashes are. You might forget a character which you needed to str_replace with a slash.
Also, that whole battery of slashes and escaping slashes doesnt make your code very readable :P

Settings that could influence PHP str_replace behaviour

I am currently working on a replacement tool that will dynamically replace certain strings (including html) in a website using a smarty outputfilter.
For the replacement to take place, I am using PHP's str_ireplace method, which reads the code that is supposed to be replaced and the replacement code from a database, and then pass the result to the smarty output (using an output filter), in a similar way as the below.
$tpl_source = str_ireplace($replacements['sourceHTML'], $replacements['replacementHTML'], $tpl_source);
The problem is, that although it works great on my dev server, once uploaded to the live server replacements occasionally fail. The same replacements work just fine on my dev version though. After some examinations and googling there was not much I could find out regarding this issue. So my question is, what could influence str_replace's behavour?
Thanks
Edit with replacement example:
$htmlsource = file_get_contents('somefile.html');
$newstr = str_replace('Some text', 'sometext', $htmlsource); // the text to be replaced does exist in the html source
fails to replace. After some checking, it looks like the combination of "> creates a problem. But just the combination of it. If I try to change only (") it works, if I try to change only (>) it works.
It might be that special chars like umlauts do not display on the live server correctly and so str_replace() would fail, if there are specialchars inside the string you want to replace.
Is the input string identical on both systems? Have you verified this? Are you sure?
Things to check:
Are the HTML attributes in the same order?
Are the attribute values using the same kind quote marks? (eg <a href='#'> vs <a href="#">)
Is there any other stray HTML code getting in there?
Is the entity encoding the same? (eg vs   - same character; different HTML)
Is the character-set the same? (eg utf-8 vs ISO 8859-1: Accented characters will be encoded differently)
Any of these things will affect the result and produce the failures you're describing.
This was a trikcy problem, and it ended up having nothing to do with the str_replace method itself;
We are using smarty as a tamplating system. The str_replace method was used by a smarty ouput filter in order to change the html in some ocassions, just before it was delivered to the user.
Here is the Smarty outputfilter Code:
function smarty_outputfilter_replace($tpl_source, &$smarty)
{
$replacements = Content::getReplacementsForPage();
if (is_array($replacements))
{
foreach ($replacements as $replacementData)
{
$tpl_source = str_replace($replacementData['sourcecode'], $replacementData['replacementcode'], $tpl_source);
}
}
return ($tpl_source);
}
So this code failed now and then for now apparent reason... until I realized that the HTML code in the smarty template was being manipulated by an Apache filter.
This resulted into the source code in the browser (which we were using as the code to be replaced by something else) not being identical to the template code (which smarty was trying to modify). Result? str_replace failed :)

Categories