tags:

views:

1494

answers:

2

Hi,

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

+1  A: 

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 :-)

Vinko Vrsalovic
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.
Amber
You can strip them as Lior shows
Vinko Vrsalovic
Yes, however that would also have a performance hit just as using concatenation would.
Amber
But I think the hit would be slower... One would have to measure.
Vinko Vrsalovic
+1  A: 

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.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html

Lior Cohen
How does opcode caching affect the speed of string concatenation?
Tom Haigh
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.
Lior Cohen