I have a variable a such $var:
$var = "One, Two, Three";
I can echo the variable without any problems the output is:
One, Two, Three
Is it possible, when echoing the variable to add a line break where there is a ,, so it would look like this?
One,
Two,
Three
If you echo the text to HTML, you can do the following:
echo str_replace(",", ", <br/>", $var);
If you echo the string to a console or a text file through redirection, just use the PHP_EOL constant, which represents the correct end-of-line string for the current platform ie. "\n" for Unix, "\r\n" for Windows:
echo str_replace(",", "," . PHP_EOL, $var);
You can use this:
$var = "One,\nTwo,\nThree";
\n is the line break, and makes sense if you are working through the terminal
You use \n to force a new line when outputting to a terminal.
$var = "One,\nTwo,\nThree";
You can use the HTML <br /> to output a new line on a web browser.
$var = "One,<br />Two,<br />Three";
You can use the str_replace function once you determine which type you want.
Make use of <br> tag
$var = "One, <br>Two, <br>Three";
(or) Make use of str_replace in PHP
<?php
$var = "One, Two, Three";
echo str_replace(',',',<br>',$var); // code replaces all your commas with , and a <br> tag
Explode the string with the comma as separator, then iterate through the resulting array, adding line breaks (with the br tag if outputting to browser, or newline (\n) escape sequence if outputting to terminal) when needed?
Related
How to set an element of an array as a line break?
For example:
$array(1,2,3,'\n');
I try to set the element as '\n' but It will print exactly '\n', not a line break when imploded.
implode('',$array);
Use double quotes "\n" instead of '\n' single quotes, Single quotes treats as string
<?php
$arr = [1,2,3,"\n","after line break"];
echo implode('',$arr);
?>
Live demo : https://eval.in/865569
In your browser to add line break use <br> instead \n
How can I find and replace the same characters in a string with two different characters? I.E. The first occurrence with one character, and the second one with another character, for the entire string in one go?
This is what I'm trying to do (so users need not type html in the body): I've used preg_replace here, but I'll willing to use anything else.
$str = $str = '>>Hello, this is code>> Here is some text >>This is more code>>';
$str = preg_replace('#[>>]+#','[code]',$str);
echo $str;
//output from the above
//[code]Hello, this is code[code] Here is some text [code]This is more code[code]
//expected output
//[code]Hello, this is code[/code] Here is some text [code]This is more code[/code]
But problem here is, both >> get replaced with [code]. Is it possible to somehow replace the first >> with [code] and the second >> with a [/code] for the entire output?
Does php have something to do this in one go? How can this be done?
$str = '>>Hello, this is code>> Here is some text >>This is more code>>';
echo preg_replace( "#>>([^>]+)>>#", "[code]$1[/code]", $str );
The above will fail if something like the following is your input:
>>Here is code >to break >stuff>>
To deal with this, use negative lookahead:
#>>((?!>[^>]).+?)>>#
will be your pattern.
echo preg_replace( "#>>((?!>[^>]).+?)>>#", "[code]$1[/code]", $str );
I am running a RST to php conversion and am using preg_match.
this is the rst i am trying to identify:
An example of the **Horizon Mapping** dialog box is shown below. A
summary of the main features is given below.
.. figure:: horizon_mapping_dialog_horizons_tab.png
**Horizon Mapping** dialog box, *Horizons* tab
Some of the input values to the **Horizon Mapping** job can be changed
during a Workflow using the internal programming language, IPL. For
details, refer to the *IPL User Guide*.
and I am using this regex:
$match = preg_match("/.. figure:: (.*?)(\n{2}[ ]{3}.*\n)/s", $text, &$result);
however it is returning as false.
here is a link of the expression working on regex
http://regex101.com/r/oB3fW7.
Are you sure that the line break is \n, is doubt, use \R:
$match = preg_match("/.. figure:: (.*?)(\R{2}[ ]{3}.*\R)/s", $text, &$result);
\R stands for either \n, \r and \r\n
My instinct would be to do some troubleshooting around the s flag as well as the $result variable passed by reference. To achieve the same without any interference from dots and the return variable, can you please try this regex:
..[ ]figure::[ ]([^\r\n]*)(?:\n|\r\n){2}[ ]{3}[^\r\n]*\R
In code, please try exactly like this:
$regex = "~..[ ]figure::[ ]([^\r\n]*)(?:\n|\r\n){2}[ ]{3}[^\r\n]*\R~";
if(preg_match($regex,$text,$m)) echo "Success! </br>";
Finally:
If this does not working, you might have a weird Unicode line break that php is not catching. To debug, for each character of your string, iterate through all the string's characters
Iterate: foreach(str_split($text) as $c) {
Print the character: echo $c . " value = "
Print the value from this function: . _uniord($c) . "<br />"; }
I am trying to pass a string to a javascript function which opens that string in an editable text area. If the string does not contain a new line character, it is passed successfully. But when there is a new line character it fails.
My code in PHP looks like
$show_txt = sprintf("showEditTextarea('%s')", $test_string);
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.$show_txt.';return false;">';
And the javascript function looks like -
$output[] = '<script type="text/javascript">
var showEditTextarea = function(test_string) {
alert(test_string);
}
</script>';
The string that was successfully passed was "This is a test" and it failed for "This is a first test
This is a second test"
Javascript does not allow newline characters in strings. You need to replace them by \n before the sprintf() call.
You are getting this error because there is nothing escaping your javascript variables... json_encode is useful here. addslashes will also have to be used in the context to escape the double quotes.
$show_txt = sprintf("showEditTextarea(%s)", json_encode($test_string));
$output[] = '<a href="#" id="link-'.$data['test'].'" onclick="'.htmlspecialchars($show_txt).';return false;">';
Why don't you try replacing all spaces in the php string with \r\n before you pass it to the JavaScript function? See if that works.
If that does not work then try this:
str_replace($test, "\n", "\n");
Replacing with two \ may work as it will encapsulate.
I would avoid storing HTML or JS in PHP variables as much as possible, but if you do need to store the HTML in a PHP variable then you will need to escape the new line characters.
try
$test_string = str_replace("\n", "\\\n", $test_string);
Be sure to use double quotes in the str_replace otherwise the \n will be interpreted as literally \n instead of a new line character.
Try this code, that deletes new lines:
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '', $test_string));
Or replaces with: \n.
$show_txt = sprintf("showEditTextarea('%s')", str_replace(PHP_EOL, '\n', $test_string));
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
How do I convert each new line to paragraph?
$variable should become:
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>
Try this:
$variable = str_replace("\n", "</p>\n<p>", '<p>'.$variable.'</p>');
The following should do the trick :
$variable = '<p>' . str_replace("\n", "</p><p>", $variable) . '</p>';
Be careful, with the other proposals, some line breaks are not catch.
This function works on Windows, Linux or MacOS :
function nl2p($txt){
return str_replace(["\r\n", "\n\r", "\n", "\r"], '</p><p>', '<p>' . $txt . '</p>');
}
$array = explode("\n", $variable);
$newVariable = '<p>'.implode('</p><p>', $array).'</p>'
<?php
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
$prep0 = str_replace(array("\r\n" , "\n\r") , "\n" , $variable);
$prep1 = str_replace("\r" , "\n" , $prep0);
$prep2 = preg_replace(array('/\n\s+/' , '/\s+\n/') , "\n" , trim($prep1));
$result = '<p>'.str_replace("\n", "</p>\n<p>", $prep2).'</p>';
echo $result;
/*
<p>Afrikaans</p>
<p>Shqip - Albanian</p>
<p>Euskara - Basque</p>
*/
?>
Explanation:
$prep0 and $prep1: Make sure each line ends with \n.
$prep2: Remove redundant whitespace. Keep linebreaks.
$result: Add p tags.
If you don't include $prep0, $prep1 and $prep2, $result will look like this:
<p>Afrikaans
</p>
<p>Shqip - Albanian
</p>
<p>Euskara - Basque</p>
Not very nice, I think.
Also, don't use preg_replace unless you have to. In most cases, str_replace is faster (at least according to my experience). See the comments below for more information.
Try:
$variable = 'Afrikaans
Shqip - Albanian
Euskara - Basque';
$result = preg_replace("/\r\n/", "<p>$1</p>", $variable);
echo $result;
I know this is a very old thread, but I want to highlight, that suggested solutions can have some issues in HTML world:
They do not check whether there is already a p tag around respective paragraph. This can result in extra paragraphs. At least some browsers will then show this as extra paragraphs, meaning <p>line1<p>line2</p>line3</p> will result in 3 paragraphs, which may not be the intention.
In fact, there is a bunch of tags, that are not expected inside of p, as per the spec of phrasing content. Or rather there is a limited set of tags, tha can be.
They will change new lines inside tags, where you want to preserve new lines as is. pre and textarea are the ones, where you could generally want that. code, samp, kbd and var are an example of other common values, but technically it can be any tag with white-space CSS property set to either pre, pre-wrap, pre-line or break-spaces.
They usually only check for \r\n or just \r or \n, while there are actually more symbols, that would mean new line, and they also have respective HTML entities, which can easily occur in HTML string.
To "combat" these flaws, at least, to an extent, I've just released a nl2tag library, which can also "convert" new lines to <li> items and has an "improved" nl2br logic (mostly for the sake of whitespace retention).
It's far from perfect (check the readme for limitations), but should cover you in case of relatively simple HTML string.