Viewed   90 times

I have a php parser that split a given string by line-breaks, doing something like this:

$lines = explode(PHP_EOL,$content);

The parser works fine when working on server side. However, when I pass the content via post by ajax (using jquery's $.post method) the problem arises: line breaks are not recogniezed. So after almost an hour of tests and head-aches I decided to changed PHP_EOL by "n" and it worked:

$lines = explode("n",$content);

Now it works! Damn it I lost so much time! Could somebody explain me when use PHP_EOL and "n" properly, so I can save time in the future? Appreciate your kind answers ;)

 Answers

5

The constant PHP_EOL should generally be used for platform-specific output.

  • Mostly for file output really.
  • Actually the file functions already transform n ?? rn on Windows systems unless used in fopen(…, "wb") binary mode.

For file input you should prefer n however. While most network protocols (HTTP) are supposed to use rn, that's not guaranteed.

  • Therefore it's best to break up on n and remove any optional r manually:

    $lines = array_map("rtrim", explode("n", $content));
    

    Or use the file(…, FILE_IGNORE_NEW_LINES) function right away, to leave EOL handling to PHP or auto_detect_line_endings.

  • A more robust and terser alternative is using preg_split() and a regexp:

    $lines = preg_split("/R/", $content);
    

    The R placeholder detects any combination of r + n. So would be safest, and even work for Classic MacOS ? 9 text files (rarely seen in practice).

    Obligatory microoptimization note:
    While regex has a cost, it's surprisingly often speedier than manual loops and string postprocessing in PHP.

And there are a few classic examples where you should avoid PHP_EOL due to its platform-ambiguity:

  • Manual generation of network protocol payloads, such as HTTP over fsockopen().
  • For mail() and MIME construction (which really, you shouldn't do tediously yourself anyway).
  • File output, if you want to consistently write just Unix n newlines regardless of environment.

So use a literal "rn" combination when not writing to files, but preparing data for a specific context that expects network linebreaks.

Wednesday, August 10, 2022
5

You can use $.trim() to remove extra white-space in a string.

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.

Source: http://api.jquery.com/jquery.trim

Ex.

function mysubmit{
    var contentbox      = $("#contentbox").html(),
        contentboxvalue = "contentboxvalue ='" + escape($.trim(contentbox)) + "'";
    $.ajax({
        type    :"POST",
        url     : "<?php echo base_url() ?>admin/data",
        data    : contentboxvalue,
        cache   : true,
        success : function() {
            document.getElementById("contentboxInfo").innerHTML = contentbox;
        }
    });
}
Saturday, October 29, 2022
 
caesay
 
2

I think you've summarised the advantages quite well. You are however missing one point. The decimal type is only more accurate at representing base 10 numbers (e.g. those used in currency/financial calculations). In general, the double type is going to offer at least as great precision (someone correct me if I'm wrong) and definitely greater speed for arbitrary real numbers. The simple conclusion is: when considering which to use, always use double unless you need the base 10 accuracy that decimal offers.

Edit:

Regarding your additional question about the decrease in accuracy of floating-point numbers after operations, this is a slightly more subtle issue. Indeed, precision (I use the term interchangeably for accuracy here) will steadily decrease after each operation is performed. This is due to two reasons:

  1. the fact that certain numbers (most obviously decimals) can't be truly represented in floating point form
  2. rounding errors occur, just as if you were doing the calculation by hand. It depends greatly on the context (how many operations you're performing) whether these errors are significant enough to warrant much thought however.

In all cases, if you want to compare two floating-point numbers that should in theory be equivalent (but were arrived at using different calculations), you need to allow a certain degree of tolerance (how much varies, but is typically very small).

For a more detailed overview of the particular cases where errors in accuracies can be introduced, see the Accuracy section of the Wikipedia article. Finally, if you want a seriously in-depth (and mathematical) discussion of floating-point numbers/operations at machine level, try reading the oft-quoted article What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Sunday, November 20, 2022
 
3

Why don't you try constructing your data like this

var postData = {};
$('#items tr').not(':first').each(function(index, value) {
    var keyPrefix = 'data[' + index + ']';
    postData[keyPrefix + '[supp_short_code]'] = $(this).closest('tr').find('.supp_short_code').text();
    postData[keyPrefix + '[project_ref]'] = $(this).closest('tr').find('.project_ref').text();
    // and so on
});

Then in your AJAX call

data: postData,

Now your PHP script can process the data as a multi-dimensional array

<?php
if (isset($_POST['data']) && is_array($_POST['data'])) {
    foreach ($_POST['data'] as $row => $data) {
        echo $data['supp_short_code'];
        echo $data['project_ref'];
        // and so on
    }
}
Saturday, December 17, 2022
 
myitcv
 
4

Generally for path related operations you should prefer NSURL over NSString because the path information can be stored more efficiently in NSURL (according to the class reference for NSFileManager). So I would recommend that for your APIs you use also NSURL.

Also NSURL has URLByAppendingPathComponent: and URLByAppendingPathExtension: so convenience is served as well :-)

Wednesday, October 26, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :