Is there a PHP string function that transforms a multi-line string into a single-line string?
I'm getting some data back from an API that contains multiple lines. For example:
<p>Some Data</p>
<p>Some more Data</p>
<p>Even More Data</p>
I assign that data to a variable, then echo the variable as part/"cell" of a CSV document.
It's breaking my CSV document. Instead of all content showing in one cell (when viewing in OpenOffice Calc), it shows in multiple cells and rows. It should be contained within one cell.
I would like to transform the string into:
<p>Some Data</p><p>Some more Data</p><p>Even More Data<p>
Or, what is the best fix for this?
Copy and Paste the multiline text. Once copied, click the "convert" option to convert the text into a single line. It takes a while to get you the text in a single line. Once the text is converted into a single line, you can clear the content using the "clear" option.
The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted. Return value: This function returns a string.
You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.
You simply need to remove all new line (\n) and carriage return (\r) characters from the string. In PHP this is as simple as:
$string = str_replace(array("\n", "\r"), '', $string);
To remove anything unnecessary between the closing and opening </p>...<p> tags you can use a regular expression. I haven't cleaned it up so it's just for reference.
$str = preg_replace("/(\/[^>]*>)([^<]*)(<)/","\\1\\3",$str);
It will strip anything between the p tags, such as newlines, whitespace or any text.
And again with the delete-only-linebreaks-and-newlines approach
$str = preg_replace("/[\r\n]*/","",$str);
Or with the somewhat faster but inflexible simple-string-replacement approach
$str = str_replace(array("\r","\n"),"",$str);
Take a pick!
Let's compare my methods
Performance is always relative to the fastest approach in this case the second one.
(Lower is better)
Approach 1 111
Approach 2 300
Approach 3 100
Approach 1
Strips everything between tags
Approach 2 and 3
Strips newline and linebreak characters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With