PHP long string without newline

12,580

Solution 1

This is the right code, that solved all issues:

$myStr = "
    here is my string
    and it is spread across multiple lines
  ";
  $myStr = str_replace(array("\r","\n"), "", $myStr);  

It is based on Lior Cohen's answer, but it also strips carriage returns "\r".

Solution 2

With the heredoc syntax (or nowdoc, depending on your needs, check the documentation link):

$multiline = <<<EOT
My name is "$name". I am printing some $foo->foo.
This should print a capital 'A': \x41
EOT;
$singleline = str_replace("\n","",$multiline);

But this sucks... sorry :-)

Solution 3

You could strip newline characters from the string:

  $myStr = "
    here is my string
    and it is spread across multiple lines
  ";
  $myStr = str_replace("\n", "", $myStr);  

You should still use the concatenation operator (.) for such things. The performance penalty here is negligible if you're using opcode caching (APC) and this would really not be anything noticeable when taking DB access and additional logic (including loops) into the run time equation.

Update:

Give the page below a read. The conclusion above is not readily available in the text, but a careful examination should show it is valid.

http://blog.golemon.com/2006/06/how-long-is-piece-of-string.html

Share:
12,580
Yaniv
Author by

Yaniv

Updated on June 20, 2022

Comments

  • Yaniv
    Yaniv almost 2 years

    I have a long string in php which does not contain new lines ('\n').

    My coding convention does not allow lines longer than 100 characters.

    Is there a way to split my long string into multiple lines without using the . operator which is less efficient - I don't need to concat 2 strings as they can be given as a single string.

    Thanks!

    Y

  • Amber
    Amber over 14 years
    The problem with heredoc is that it will include the newline characters in the string, which would then have to be stripped out to get the "string which does not contain newlines" that the question specified.
  • Tom Haigh
    Tom Haigh over 14 years
    How does opcode caching affect the speed of string concatenation?
  • Amber
    Amber over 14 years
    Yes, however that would also have a performance hit just as using concatenation would.
  • Vinko Vrsalovic
    Vinko Vrsalovic over 14 years
    But I think the hit would be slower... One would have to measure.
  • Lior Cohen
    Lior Cohen over 14 years
    The parser would treat strings with no dynamic elements to be one long string, dropping the concatenation operators. I've dug into this subject a while ago. Will update this answer with the related article once I manage to find it again.