PHP explode function End of Line detection - php

I'm using the explode function in tandem with the implode to take a CSV text and make it display clearly on screen, like so:
$CSV_STRING = 'Quarterly update,,
Question Topic,Question Title,Question Text
Question Topic,Question Title,Question Text';
----------------------
$array = explode(PHP_EOL, $CSV_STRING);
$arrayImploded = implode("<br>", $array);
$arrayExploded = explode(",", $arrayImploded);
$arrayFinal = implode("<br>", $arrayExploded);
echo $arrayFinal;
My issue here is that I'm trying to detect the new line with PHP_EOL and it doesn't seem to detect it. I've used \n and \n\r to similar results.
What should I use to correctly display my results like so:
Quarterly update
Question Topic
Question Title
Question Text
Question Topic
Question Title
Question Text
Thank you!

Rather than exploding/imploding, you should be able to run it through nl2br() which will convert the new lines to <br /> tags and then if you just use str_replace() to replace the commas with <br /> tags as well, it should display as you want...
$CSV_STRING = 'Quarterly update,,
Question Topic,Question Title,Question Text
Question Topic,Question Title,Question Text';
$out = nl2br($CSV_STRING);
$out = str_replace("<br />", "<br /><br />", $out);
echo str_replace(",", "<br>", $out);
To create an extra break between the blocks, this just adds another <br /> tag to each one just added.
Note that I've used <br> rather than <br /> so you should see which part of the code is changing which part of the original string. But use <br /> for 'correctness'.

Related

str_ireplace or preg_replace replaced break tag into \r\n

I have read this post that discuss about converting html break tag into a new line in php. Other people said it's work for them but something weird happened to me.
this is the code I use:
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);`
and this is the code they use :
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
both insert "\r\n" into the text , why is this happening ?
screenshot:
if there's any previous post / PHP method let me know
EDIT : adding my code that echo the textbox
<-- THIS WONT WORK -->
$username = $_SESSION['username'];
$unsafenomorsoal = $_POST['nomorsoal'];
$unsafejawaban = $_POST['jawaban'];
$nomorsoal = mysqli_real_escape_string($konek,$unsafenomorsoal);
$jawabannotcut = substr($unsafejawaban,0,50000);
$unsafejawabanfirst = nl2br($jawabannotcut);
$jawaban1 = mysqli_real_escape_string($konek,$unsafejawabanfirst);
$breaks = array("<br />","<br>","<br/>");
$jawaban = str_ireplace($breaks, PHP_EOL, $jawaban1);
$_SESSION['textvaluejawaban'] = $jawaban;
and this is what echoed :
echo "<div class=\"head-main-recent-background\" style=\"background:white;width:99%;color:black;text-align:left;height:1000px;position:relative;top:130px;margin-top:10px;\">- Jawab Soal -<br/>".$jawabanerror."<br/>Nama : ".$_SESSION['username']."<br/>
<form method=\"post\" action=\"prosesjawabsoal.php\">
<input type=\"hidden\" name=\"nomorsoal\" value=\"".$_SESSION['nomorsoal']."\"/>
Jawaban : <br/>
<textarea placeholder=\"Max 40.000 Huruf\" style=\"overflow- x:none;width:99%;height:300px;\" type=\"text\" name=\"jawaban\" maxlength=\"40000\" >".$_SESSION['textvaluejawaban']."</textarea>
<br/>Captcha <br/>
<div style=\"overflow:hidden;\" class=\"g-recaptcha\" data- sitekey=\"6LfYQicTAAAAAFstkQsUDVgQ60x_93obnKAMKIM9\"></div><br/>
<button type=\"submit\" name=\"submit\" style=\"margin-top:10px;height:auto;width:auto;\">Kirim Jawaban</button>
</form>
</div>";
Note : The snippet won't work because it's php
Sorry i used snippet due to error while posting the code !
EDIT :
tried preg_replace() method but still same result
EDIT :
change title to tell that preg_replace not work
Your problem is the mysqli_real_escape_string(). The converts the "\r\n" into a string to make it safe to input into the database. Remove it completely. Instead use htmlspecialchars when you output to screen:
echo htmlspecialchars($myUnsafeVar);
Apply these rules (as a starting point, there's always possible exceptions, but in rare cases):
use mysqli_real_escape_string when inputting strings into a database. It won't do what you expect when outputting to screen - so anything that has been mysql escaped() should not appear on screen.
use htmlspecialchars (which you don't have!) when outputting to screen.
use url_encode for adding stuff into a URL
There are also many different "escape" function (e.g. inserting into JSON, inserting into mysql, inserting into other databases). Use the right one for what you need - and don't use it for other purposes.
Check the functions for more details.
As it currently stands your code is not safe even with all those efforts - but it's really simple to fix!
try with preg_replace() function and no need of \n\r both you can do with \n or PHP_EOL only
$jawaban = preg_replace('#<br\s*?/?>#i', "\n", $jawaban1);
or
$jawaban = preg_replace('#<br\s*?/?>#i', PHP_EOL, $jawaban1);
you must knowing these before working with strings:
"\n\r" means new line.
'\n\r' doesn't mean new line.
doesn't mean new line. It's just HTML number for HTML Symbols. when you are using it, you mean just show \n\r in your browser. this is answer to your question:
both insert "\r\n" into the text , why is this happening?
so, after knowing that, you understand:
if your $jawaban1 string is
Hello <br> and welcome!
and your code is
$breaks = array("<br />", "<br>", "<br/>");
$jawaban = str_ireplace($breaks, "
", $jawaban1);
It means, $jawaban will be exactly like this:
Hello
and welcome!
without any \n\r and just your browser showing it like this:
Hello \n\r and welcome!
If you want to replace all br by \n\r just use the code in your question:
$breaks = array("<br />", "<br>", "<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
About preg_replace()
When you can use str_ireplace, Don't use preg_replace. str_ireplace is faster.
Don't do it if you don't need it
in your code you did this:
$unsafejawabanfirst = nl2br($jawabannotcut);
and right after that you want to replace br with \n\r. It's like do and undo. I see that you are trying to show it again inside textarea element. so don't replace \n\r with br. the solution? don't change \n\r at all and if you want save it to the db just save it with \r\r. when you need it to show outside of textarea element just use nl2br function.
There is always something that saves my day, it is actually a workaround and your question is a trigger for me to get deeper to this matter - once for all.
For now, here you go - nice & sleek workaround:
There is already nl2br() function that replaces inserts <br> tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

replace text in single line after specific occurence using regex

I have searched for a solution to a problem on this site but have not found a way to do this task using regex (or perhaps something just shortened that uses less memory).
I am attempting to parse a string where text after a specific pattern (& the pattern itself) is to be removed from the same line. The text prior to to the pattern and also any line not containing the search pattern should be unedited.
Here is a working example:
$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.<br />
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
done.<br />';
$remove = '[test]';
$lines = preg_split('/\r?\n/', $text);
foreach ($lines as $line)
{
$check = substr($line, 0, stripos($line, $remove));
$new[] = !empty($check) ? $check . '<br />' : $line;
}
$newText = implode($new);
echo $newText;
The above code works as expected but I would like to know how to do this using regex or perhaps something that uses a lot less code and memory. I have attempted to do this using regex from examples on this site + some tinkering but have not been able to get the result that is required. The solution should also use code that is compatible with PHP 5.5 syntax (no \e modifier). Using an array for the removal pattern will also be fitting as I may need to do a search for multiple patterns (although it is not shown in my example).
Thank you.
Thanks to frightangel for showing me the proper regex pattern.
Below is the necessary code to accomplish what was asked above:
$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.<br />
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
[bbc]done.<br />
[another]this line should not be affected.<br />
it works!!<br />';
$removals = array('[test]', '[bbc]');
$remove = str_replace(array('[', ']'), array('~\[', '\].*?(?=\<br\s\/\>|\\n|\\r)~mi'), $removals);
$text = preg_replace($remove, '', $text);
echo $text;
The text that it searches for actually comes from a mysql query that feeds an array so I changed what is shown above to use what will more or less be used ($removals being that array).
The only problem left for me is that if text was prior to the removal then it would be better to leave the final line break from that line instead of omitting it. It should only be omitted if all text from a single line is removed.
Try this way:
$text = 'This is a test to remove single lines.<br />
The line below has the open type bbcode (case insensitive) that is to be removed.<br />
The text on the same line that follows the bbcode should also be removed.
this text should remain[test]this text should be removed on this line only!<br />
the other lines should remain.<br />
done.<br />';
$remove = 'test';
$text = preg_replace("/\[$remove\].*(?=\<br\s\/\>)/m", '', $text);
$text = preg_replace("/^(\<br\s\/\>)|(\\n)|(\\r)$/m","",$text);
echo $text;
Here's regex explanation: http://regex101.com/r/nW1bG8
try this, and tell me if thats what you want
if not, tell me, i probably didnt understand your question
preg_replace("/\[\S+\].+<[^>]+\s?\/>|<[^>]+\s?\/>/m","",$text);

preg_replace question

I'm trying to use preg_replace to strip out a section of code but I am having problems getting it to work right.
Code Example:
$str = '<p class="code">some string here</p>';
PHP I'm using:
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
preg_replace($pattern,"", $str);
This strips out the code just as I want with the exception of the space between the p and class.
Returns:
some string here //notice the single space at the beginning.
I'm trying to get:
some string here //no space at the beginning.
I have been beating my head against the wall trying to find a solution. The reason I'm trying to strip it out in a chunk instead of breaking the preg_replace into pieces is because I don't want to change anything that may be in the string between the tags. Any ideas?
That does not happen for me (and it shouldn't).
It may be a space output somewhere else (use var_dump() to view the string).
You might want to look into this thread to see if you want to switch to using DOMDocument. It'll save you a great deal of headaches trying to parse through HTML.
Robust and Mature HTML Parser for PHP
test:
<?php
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$result = preg_replace($pattern,"", $str);
var_dump($result);
result:
php pregrep.php
string(16) "some string here"
seems to work just fine.
Alex I figured out where I was picking up the extra space.
I was putting that code into a text area like this:
$str = '<p class="code">some string here</p>';
$pattern = array();
$pattern[0] = '!<p class="code">!';
$pattern[1] = '!</p>!';
$strip_str = preg_replace($pattern,"", $str);
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5">
<?php echo $strip_str; ?>
</textarea>
This gave me my extra space but when I changed the code to:
<textarea id="code_area" class="syntaxhl" name="code" cols="66" rows="5"><?php echo $strip_str; ?></textarea>
No line spaces or breaks the extra space went away.
Why not use trim()?
$text = trim($text);
This removes white spaces around strings.

How to remove redundant <br /> tags from HTML code using PHP?

I'm parsing some messy HTML code with PHP in which there are some redundant tags and I would like to clean them up a bit. For instance:
<br>
<br /><br />
<br>
How would I replace something like that with this using preg_replace()?:
<br /><br />
Newlines, spaces, and the differences between <br>, <br/>, and <br /> would all have to be accounted for.
Edit: Basically I'd like to replace every instance of three or more successive breaks with just two.
Here is something you can use. The first line finds whenever there is 2 or more <br> tags (with whitespace between and different types) and replace them with wellformated <br /><br />.
I also included the second line to clean up the rest of the <br> tags if you want that too.
function clean($txt)
{
$txt=preg_replace("{(<br[\\s]*(>|\/>)\s*){2,}}i", "<br /><br />", $txt);
$txt=preg_replace("{(<br[\\s]*(>|\/>)\s*)}i", "<br />", $txt);
return $txt;
}
This should work, using minimum specifier:
preg_replace('/(<br[\s]?[\/]?>[\s]*){3,}/', '<br /><br />', $multibreaks);
Should match appalling <br><br /><br/><br> constructions too.
this will replace all breaks ... even if they're in uppercase:
preg_replace('/<br[^>]*>/i', '', $string);
Try with:
preg_replace('/<br\s*\/?>/', '', $inputString);
Use str_replace, its much better for simple replacement, and you can also pass an array instead of a single search value.
$newcode = str_replace("<br>", "", $messycode);

How to remove <br /> tags and more from a string?

I need to strip all <br /> and all 'quotes' (") and all 'ands' (&) and replace them with a space only ...
How can I do this? (in PHP)
I have tried this for the <br />:
$description = preg_replace('<br />', '', $description);
But it returned <> in place of every <br />...
Thanks
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
http://php.net/manual/en/function.strip-tags.php
You can use str_replace like this:
str_replace("<br/>", " ", $orig );
preg_replace etc uses regular expressions and that may not be what you want.
If str_replace() isnt working for you, then something else must be wrong, because
$string = 'A string with <br/> & "double quotes".';
$string = str_replace(array('<br/>', '&', '"'), ' ', $string);
echo $string;
outputs
A string with double quotes .
Please provide an example of your input string and what you expect it to look like after filtering.
To manipulate HTML it is generally a good idea to use a DOM aware tool instead of plain text manipulation tools (think for example what will happen if you enounter variants like <br/>, <br /> with more than one space, or even <br> or <BR/>, which altough illegal are sometimes used). See for example here: http://sourceforge.net/projects/simplehtmldom/
To remove all permutations of br:
<br> <br /> <br/> <br >
check out the user contributed strip_only() function in
http://www.php.net/strip_tags
The "Use the DOM instead of replacing" caveat is always correct, but if the task is really limited to these three characters, this should be o.k.
Try this:
$description = preg_replace('/<br \/>/iU', '', $description);
$string = "Test<br>Test<br />Test<br/>";
$string = preg_replace( "/<br>|\n|<br( ?)\/>/", " ", $string );
echo $string;
This worked for me, to remove <br/> :
(> is recognised whereas > isn't)
$temp2 = str_replace('<','', $temp);
// echo ($temp2);
$temp2 = str_replace('/>','', $temp2);
// echo ($temp2);
$temp2 = str_replace('br','', $temp2);
echo ($temp2);

Categories