How to remove carriage returns from output of string?

前端 未结 7 897
无人及你
无人及你 2020-12-08 04:30

I am using wordpress as a CMS and trying to allow user fields to be input to populate the info windows in a Google Map script. I am using this to select the id and pull in

相关标签:
7条回答
  • 2020-12-08 04:49

    I always use this to get rid of pesky carriage returns:

    $string = str_replace("\r\n", "\n", $string); // windows -> unix
    $string = str_replace("\r", "\n", $string);   // remaining -> unix
    
    0 讨论(0)
  • 2020-12-08 04:50

    I don't fully understand your exact problem, but the answer to the title of your question is quite simple:

    $snip = str_replace('.', '', $snip); // remove dots
    $snip = str_replace(' ', '', $snip); // remove spaces
    $snip = str_replace("\t", '', $snip); // remove tabs
    $snip = str_replace("\n", '', $snip); // remove new lines
    $snip = str_replace("\r", '', $snip); // remove carriage returns
    

    Or a all in one solution:

    $snip = str_replace(array('.', ' ', "\n", "\t", "\r"), '', $snip);
    

    You can also use regular expressions:

    $snip = preg_replace('~[[:cntrl:]]~', '', $snip); // remove all control chars
    $snip = preg_replace('~[.[:cntrl:]]~', '', $snip); // above + dots
    $snip = preg_replace('~[.[:cntrl:][:space:]]~', '', $snip); // above + spaces
    

    You'll still need to use addslashes() to output $snip inside Javascript.

    0 讨论(0)
  • 2020-12-08 04:51

    Try JSON-encoding it, I always do that when I send data from PHP to Javascript. It solves most encoding issues, including newlines.

    0 讨论(0)
  • 2020-12-08 04:58

    if you need to remove new line symbols of all types (in utf8)

    $dataWithoutCarrierReturn = preg_replace('/\R/', '', $inData);
    
    0 讨论(0)
  • 2020-12-08 04:59

    Use WP's own esc_js(), which will escape quotes and line breaks for JavaScript strings.

    0 讨论(0)
  • 2020-12-08 05:07

    Since you're putting this into Javascript, you'll need to escape it for javascript strings. addslashes() should do the trick.

    0 讨论(0)
提交回复
热议问题