Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP long string without newline

Tags:

string

php

break

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

like image 960
Yaniv Avatar asked Aug 18 '09 12:08

Yaniv


3 Answers

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".

like image 188
Pascal Klein Avatar answered Nov 03 '22 11:11

Pascal Klein


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

like image 26
Vinko Vrsalovic Avatar answered Nov 03 '22 10:11

Vinko Vrsalovic


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

like image 1
Lior Cohen Avatar answered Nov 03 '22 11:11

Lior Cohen