Break a string and print line by line - php

I have a long string as a single line (its too long) and I want it to break and print as a new line whenever we meet a semi colon ; and } or { for example
This is my string:
aaaaaaaaaaa;bbbbbbbbbb{ccccccccc;dddddddd;}eeeeeee{fffffff;}
I want to print it as below:
aaaaaaaaaaa;
bbbbbbbbbb{
ccccccccc;
dddddddd;
}
eeeeeeee{
fffffffffff;
}
Even if ; and } meet together I wanna break it down and print in two lines.
For example jjjjjjjjjjjjj;} might display as
jjjjjjjjjjj;
}
Please help me.

You can simply use preg_replace as
$str = 'aaaaaaaaaaa;bbbbbbbbbb{ccccccccc;dddddddd;}eeeeeee{fffffff;}';
$res = preg_replace('/(;|{|})/',"$1\n",$str);
print_r($res);
Output :
aaaaaaaaaaa;
bbbbbbbbbb{
ccccccccc;
dddddddd;
}
eeeeeeee{
fffffffffff;
}
Regex
Demo

You can use preg_replace(/([;\{\}])/, '$1<br/>', $sourceLine) for HTML output. If outputing to file, change '$1<br/>' to "$1\r\n"

You can use like the below code also :
$str = 'aaaaaaaaaaa;bbbbbbbbbb{ccccccccc;dddddddd;}eeeeeee{fffffff;}';
$arr_replace_char = array(';','{','}');
$arr_replace_by = array(';<br>','{<br>','}<br>');
echo str_replace($arr_replace_char,$arr_replace_by,$str);

Related

PHP & HTML <a href> leaving extra space?

I have the following PHP code
$links = fopen("./links/links.txt", "r");
if ($links) {
while (($line = fgets($links)) !== false) {
$linkData = explode(" ", $line);
/// The line below is the problematic one
echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}
fclose($links);
} else {
die('Error opening file, try refreshing.');
}
You can see I've seperated the line I'm having issues with. I have the following file links.txt
http://example.com Example
http://example2.com Example2
Basically this will add the URL in the text file to an anchor tag, and it'll add the text next to it, as the anchor display text. It works, but for some reason, every anchor tag ends with a space, except the last one. Anyone know why this is and how I can fix it?
The string that fgets() returns includes the newline that separates the lines. This will be at the end of $linkData[1], so you're writing
<a href='http://example.com' class='links-item'>Example
</a><br>
to the output.
You could instead use fgetcsv(), specifying space as the field delimiter. This will explode the line for you and automatically ignores the newlines.
while (($linkData = fgetcsv($links, 0, " ")) !== false) {
echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}
fgets() captures newlines as well as word characters into the string. Use the trim function to remove unwanted whitespace:
echo "<a href='".trim($linkData[0])."' class='links-item'>".trim($linkData[1])."</a><br>";
Alternatively, as #Barmar noted, you could use fgetcsv function
use
var_dump($linkData);
To see what does fgets() returns. Maybe there are unexpected characters.
Consider to use more advanced file formatting, for example you can use csv format and use http://php.net/manual/en/function.fgetcsv.php to retrieve results from file.

Keep all html whitespaces in php mysql

i want to know how to keep all whitespaces of a text area in php (for send to database), and then echo then back later. I want to do it like stackoverflow does, for codes, which is the best approach?
For now i using this:
$text = str_replace(' ', '&nbs p;', $text);
It keeps the ' ' whitespaces but i won't have tested it with mysql_real_escape and other "inject prevent" methods together.
For better understanding, i want to echo later from db something like:
function jack(){
var x = "blablabla";
}
Thanks for your time.
Code Blocks
If you're trying to just recreate code blocks like:
function test($param){
return TRUE;
}
Then you should be using <pre></pre> tags in your html:
<pre>
function test($param){
return TRUE;
}
</pre>
As plain html will only show one space even if multiple spaces/newlines/tabs are present. Inside of pre tags spaces will be shown as is.
At the moment your html will look something like this:
function test($param){
return TRUE;
}
Which I would suggest isn't desirable...
Escaping
When you use mysql_real_escape you will convert newlines to plain text \n or \r\n. This means that your code would output something like:
function test($param){\n return TRUE;\n}
OR
<pre>function test($param){\n return TRUE;\n}</pre>
To get around this you have to replace the \n or \r\n strings to newline characters.
Assuming that you're going to use pre tags:
echo preg_replace('#(\\\r\\\n|\\\n)#', "\n", $escapedString);
If you want to switch to html line breaks instead you'd have to switch "\n" to <br />. If this were the case you'd also want to switch out space characters with - I suggest using the pre tags.
try this, works excellently
$string = nl2br(str_replace(" ", " ", $string));
echo "$string";

How do I remove html tags and other characters from a text field

The fields contains the value of : {"93":" Size:</span>XL</span>"}. I want to display only Size: XL. I have tried using the strip_tag function but have been unsuccessful. Are there any suggestions?
Try this,
Its json encoded value.
$text = '{"93":" Size:</span>XL</span>"}';
$ar = json_decode($text);
foreach($ar as $value){
echo strip_tags($value);
}
The output will be
Size:XL
Hope its fixed ..
If your tag was correct, like so:
<span>XL</span> instead of </span>XL</span>,
strip_tags() should work for you.
I verified with the following test...
$text = "<span>XL</span>";
$goodtext = strip_tags($text);
And output the results...
echo htmlentities($text)
echo "<br/>";
echo htmlentities($goodtext);
Yielded...
<span>XL</span>
XL
Your question was a bit unclear, if the field contains all there including the { brackets, then this regex in a replace should help, just replace the characters with an empty string:
/"\:"|[^A-Za-z:]|span/g
If that is not the case and you only have the second string with the spans, you could use this one:
/[^A-Za-z:]|span/g
Be warned though, it also removes spaces and only works in specific cases, eg. does not remove other tags etc.
You could apply a global regular expression match using the function preg_match_all to extract only "Size: XX" from your field.
$field = "your data fields"
$pattern = "/(Size:)<\/span>([a-z]{1,2})<\/span>/i";
preg_match_all($pattern,$field,$result,PREG_SET_ORDER);
foreach( $result as $r ) {
print($r[1]." ".$r[2].PHP_EOL);
}
Will output:
Size: XL
Size: L
...

echo characters only in one line with explode function php

here is what i want to do
i am working with php explode function trying to limit characters it prints after defined condition
{
$result=http://php.net
new line characters i don't want to print
$links =explode("://",$result);
$nows=$links[1];
echo $nows;
}
as you can see the above code will print
php.net
new line characters i don't want to print
but instead i want to stop printing after
php.net
You can replace newline characters with nothing:
$nows = str_replace("\n", "", $links[1]);
$nows = str_replace("\r", "", $nows);
echo $nows;
If you want only what is printed on the first line, try this:
$result = "php.net
and some other text";
$nows = reset(explode("\n", str_replace("\r\n", "\n", $result)));
If the part you're looking after will always be in the first line:
$result="http://php.net
new line characters i don't want to print";
$links = explode("\n",$result);
/*
$links[0] ->http://php.net
$links[1] ->new line characters i don't want to print
*/
$links =explode("://",$links[0]);
$nows=$links[1];
echo $nows;
/*
php.net
*/
Anyway , Consider giving more details about your case in order to offer a better way.
For instance , maybe regex?
Try
$nows = trim( $links[1] );
TRIM() will remove newlines among other things
Manual page
EDIT:
Well now we have the actual situation which you say is :-
$result=http://php.net</br>nameserver:ns1</br>nameserver:ns2.
Try
$t = explode( '</br>', $result );
$t1 = explode ( '://', $t[0] );
echo $t1[1];
Just as a note, if it is you that is creating this string somewhere else </br> is not a valid html tag, it should be <br> or if you are using XHTML it should be <br />.

Using PHP to Seperate Results of a txt file

I am trying to display the last 10 lines of a File and from there take those results and break them down to 10 individual lines..
Currently the code I have found from examples is:
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
echo implode($lastfifteenlines, "\n")
It display's the 10 items I need however it does not break them down onto individual lines the current results are:
1.0.0.11 1.0.0.12 1.0.0.13 1.0.0.14 1.0.0.15
I need that to instead display as:
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
Thanks in Advance for the Asistance!
\n is plain whitespace in html.
use echo implode("<br>", $lastfifteenlines) or put them in to separate divs, use a list (ul+li), etc..
use the explode function, like this
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
$impfile = implode($lastfifteenlines, '\n');
$lines = explode('\n', $impfile);
foreach ($lines as $line){
echo $line."<br>";
}
outpu will be
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
i hope that's what you want :)
Your code works fine. You just can't see the line breaks because HTML doesn't treat them as line breaks.
See the HTML source code in your browser to see the line breaks.
Possible solution
echo <pre> and </pre> tags before and after the implode.
Add header("Content-Type: text/plain"); before any output. It will cause the browser to parse the document as a text file and not HTML (note that no HTML tags will be parsed by the browser)
implode the array with a different string, <br>, which will cause a line break in HTML.
Also, your syntax is wrong, it's
implode($glue, $pieces);
And not
implode($pieces, $glue);

Categories