remove fake comments from json file - php

since json dosn't support comments I need my own function to clean my comments
My comments are css style, like this
/*comment*/
i tryed the following
$json = preg_replace("/(\/\*.?\*\/)/", "", $json);
but no luck.
thank's

echo preg_replace("#/\*.*?\*/#s", "", $json);
Notable changes:
I used # as the pattern delimiter. By doing this, I don't need to
escape forward slashes, making the regex prettier to read.
I added the s flag, which makes the . also match new line characters.
Beware, this will destroy comments inside a json string. An example json object that will get clobbered
{"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}

Use the following:
$json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments
$json = preg_replace('/\n\s*\n/', "\n", $json); // remove empty lines that can create errors
This will erase comments, multi line comments and empty lines
EDIT: as some of the guys were saying in the comments, you can use:
$json = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $json);
To remove only comments that are not found within strings.

$string = "some text /*comment goes here*/ some text again /*some comment again*/";
$string = preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $string );
echo $string; // some textsome text again

The complete php code to remove both single and multi-line comments.
$json = preg_replace('!/\*.*?\*/!s', '', $json); //Strip multi-line comments: '/* comment */'
$json = preg_replace('!//.*!', '', $json); //Strip single-line comments: '// comment'
$json = preg_replace('/\n\s*\n/', "\n", $json); //Remove empty-lines (as clean up for above)
Here a site you can test the code: https://www.phpliveregex.com
To test the first code line fill in like this picture:

Related

Wrapping String PHP

I have a problem with my code, i have this code that create image from external source of image & string. I used json to get the string.
My problem is if i used the string from json data i could not get the proper wrapping of string like this:
http://prntscr.com/dbhg4n
$url = 'https://bible-api.com/Psalm100:4-5?translation=kjv';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$string = $data->text;
But if i declare and set string directly i got the output that i want like this:
http://prntscr.com/dbhg7q
$string = "Enter into his gates with thanksgiving, and into his courts with praise: be thankful unto him, and bless his name. For the Lord is good; his mercy is everlasting; and his truth endureth to all generations.";
I dont think the error or the problem is on the code for wrapping the text on my image. I think it is on the json data. How can i fix this?
The text has \n symblols. Just replace them:
$string = preg_replace("/\n/", ' ', $data->text);
or without a regular expression:
$string = str_replace("\n", ' ', $data->text);

How to add new line in php echo

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.
The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.
I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

remove HTML from displaying in PHP

I have this text : http://pastebin.com/2Zgbs7hi
And i want to be able to remove the HTML code from it and just display the plain text but i want to keep at least one line break where there are currently a few line breaks
i have tried:
$ticket["summary"] = 'pastebin example';
$TicketSummaryDisplay = nl2br($ticket["summary"]);
$TicketSummaryDisplay = stripslashes($TicketSummaryDisplay);
$TicketSummaryDisplay = trim(strip_tags($TicketSummaryDisplay));
$TicketSummaryDisplay = preg_replace('/\n\s+$/m', '', $TicketSummaryDisplay);
echo $TicketSummaryDisplay;
that is displaying as plain text, but it shows it all as one big block of text with no line breaks at all
Maybe this will earn you some time.
<?php
libxml_use_internal_errors(true); //crazy o tags
$html = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$dom = new DOMDocument;
$dom->loadHTML($html);
$result='';
foreach ($dom->getElementsByTagName('p') as $node) {
if (strstr($node->nodeValue, 'Legal Disclaimer:')){
break;
}
$result .= $node->nodeValue;
}
echo $result;
This example should successfully store text from html into an array of strings.
After stripping all the tags, you can use preg_split with \R special character ( matches any newline sequence ) to convert string into array. That array will now have several blank values, and there will be also some amount of html non-breaking space entities, so we will check the array for empty values with array_filter() function ( it will remove all items that do not satisfy the filter conditions, in our case, an empty value ). Here are a problem with entity, because and space characters are not the same, they have different ASCII code, so trim() function will not remove spaces. Here are two possible solutions, the first uncommented part will only replace &nbsp and check for white space characters, while the second commented one will decode all html entities and also check for spaces.
PHP:
$text = file_get_contents( 'http://pastebin.com/raw.php?i=2Zgbs7hi' );
$text = strip_tags( $text );
$array = array_filter(
preg_split( '/\R/', $text ),
function( &$item ) {
$item = str_replace( ' ', ' ', $item );
return trim( $item );
// $item = html_entity_decode( $item );
// return trim( str_replace( "\xC2\xA0", ' ', $item ) );
}
);
foreach( $array as $value ) {
echo $value . '<br />';
}
Array output:
Array
(
[8] => Hi,
[11] => Ashley has explained that I need to ask for another line and broadband for the wifi to work, please can you arrange this.
[13] => Regards
[23] => Legal Disclaimer:
[24] => This email and its attachments are confidential. If you received it by mistake, please don’t share it. Let us know and then delete it. Its content does not necessarily represent the views of The Dragon Enterprise
[25] => Centre and we cannot guarantee the information it contains is complete. All emails are monitored and may be seen by another member of The Dragon Enterprise Centre's staff for internal use
)
Now you should have clear array with only items with value in it. By the way, newlines in HTML are expressed through <br />, not through \n, your example as response in a web browser still has them, but they are only visible in page source code. I hope I did not missed the point of the question.
try this get text output with line brakes
<?php
$ticket["summary"] = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$TicketSummaryDisplay = nl2br($ticket["summary"]);
echo strip_tags($TicketSummaryDisplay,'<br>');
?>
You are asking on how to add line-breaks to your "one big block of text with no line breaks at all".
Short answer
After you stripped the HTML tags, apply wordwrap with a desired text-block length
$text = wordwrap($text, 90, "<br />\n");
I really wonder, why nobody suggested that function before.
there is also chunk_split around, which doesn't take words into account and just splits after a certain number of chars. breaking words - but that's not what you want, i guess.
PHP
<?php
$text = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
/**
* Returns string without html tags, also
* removes takes control chars, spaces and " " into account.
*/
function dropHtmlTags($string) {
// remove html tags
//$string = preg_replace ('/<[^>]*>/', ' ', $string);
$string = strip_tags($string);
// control characters and "&nbsp"
$string = str_replace("\r", '', $string); // remove
$string = str_replace("\n", ' ', $string); // replace with space
$string = str_replace("\t", ' ', $string); // replace with space
$string = str_replace(" ", ' ', $string);
// remove multiple spaces
$string = preg_replace('/ {2,}/', ' ', $string);
$string = trim($string);
return $string;
}
$text = dropHtmlTags($text);
// The Answer: insert line breaks after 95 chars,
// to get rid of the "one big block of text with no line breaks at all"
$text = wordwrap($text, 95, "<br />\n");
// if you want to insert line-breaks before the legal disclaimer,
// uncomment the next line
//$text = str_replace("Regards Legal Disclaimer", "<br /><br />Regards Legal Disclaimer", $text);
echo $text;
?>
Result
first section shows your text block
second section shows the text with wordwrap applied (code from above)
Hello it can be done as follows:
$abc= file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
$abc = strip_tags("\n", $abc);
echo $abc;
Please, let me know whether it works
you may use
<?php
$a= file_get_contents('a.txt');
echo nl2br(htmlspecialchars($a));
?>
<?php
$handle = #fopen("pastebin.html", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
output is
Hi,
Ashley has explained that I need to ask for another line and broadband for the wifi to work, please can you arrange this.
Regards
Legal Disclaimer:
This email and its attachments are confidential. If you received it by mistake, please don’t share it. Let us know and then delete it. Its content does not necessarily represent the views of The Dragon Enterprise
Centre and we cannot guarantee the information it contains is complete. All emails are monitored and may be seen by another member of The Dragon Enterprise Centre's staff for internal use
You can probably write additional code to convert to spaces etc.
I'm not sure I did understand everything correctly but this seems to be your expected result:
$txt = file_get_contents('http://pastebin.com/raw.php?i=2Zgbs7hi');
var_dump(preg_replace("/(\&nbsp\;(\s{1,})?)+/", "\n", trim(strip_tags(preg_replace("/(\s){1,}/", " ", $txt)))));
//more readable
$txt = preg_replace("/(\s){1,}/", " ", $txt);
$txt = trim(strip_tags($txt));
$txt = preg_replace("/(\&nbsp\;(\s{1,})?)+/", "\n", $txt);
The strip_tags() function strips HTML and PHP tags from a string, if that is what you are trying to accomplish.
Examples from the docs:
<?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>');
?>
The above example will output:
Test paragraph. Other text
<p>Test paragraph.</p> Other text

Replacing \r\n (newline characters) after running json_encode

So when I run json_encode, it grabs the \r\n from MySQL aswell. I have tried rewriting strings in the database to no avail. I have tried changing the encoding in MySQL from the default latin1_swedish_ci to ascii_bin and utf8_bin. I have done tons of str_replace and chr(10), chr(13) stuff. I don't know what else to say or do so I'm gonna just leave this here....
$json = json_encode($new);
if(isset($_GET['pretty'])) {
echo str_replace("\/", "/", jsonReadable(parse($json)));
} else {
$json = str_replace("\/", "/", $json);
echo parse($json);
}
The jsonReadable function is from here and the parse function is from here. The str_replaces that are already in there are because I am getting weird formatted html tags like </h1>. Finally, $new is an array which is crafted above. Full code upon request.
Help me StackOverflow. You're my only hope
Does the string contain "\r\n" (as in 0x0D 0x0A) or the literal string '\r\n'? If it's the former, this should remove any newlines.
$json = preg_replace("!\r?\n!", "", $json);
Optionally, replace the second parameter "" with "<br />" if you'd like to replace the newlines with a br tag. For the latter case, try the following:
$json = preg_replace('!\\r?\\n!', "", $json);
Don't replace it in the JSON, replace it in the source before you encode it.
I had a similar issue, i used:
$p_num = trim($this->recp);
$p_num = str_replace("\n", "", $p_num);
$p_num = str_replace("\r", ",", $p_num);
$p_num = str_replace("\n",',', $p_num);
$p_num = rtrim($p_num, "\x00..\x1F");
Not sure if this will help with your requirements.

How to remove carriage returns from output of string?

I am using wordpress as a CMS and trying to allow user fields to be input to populate the info windows in a Google Map script. I am using this to select the id and pull in the content from a custom field.
It works fine unless there is any html in the custom-field which breaks the script.
I looked at htmlspcialchar and htmlentities but rather than strip everything out I would like to have it escaped so it still works and the html is intact. Any suggestions? I am pretty new to PHP and would really appreciate any pointers.
After a while I am still unable to find a great solution for this. TheDeadMedic suggested I use esc_js
but that printed all of the actual html code instead of rendering it.
Thank you to nickfs as that solution was slightly better but the script still breaks if there are any carriage returns in the output, which makes this not so great for a CMS.
Something else I tried was to use the trim function.. this is where I am at now where it works as long as no \r in the output. The $snip string, mapExcerpt field is where the returns are coming from:
<?php $post_id = 207; // Wordpress Post ID
$my_post = get_post($post_id);
$mapTitle = $my_post->post_title;
$mapIMG = get_post_meta($post_id, 'mapImage', true);
$snip = get_post_meta($post_id, 'mapExcerpt', true);
$lat = get_post_meta($post_id, 'lat', true);
$long = get_post_meta($post_id, 'long', true);
$pass_to = '<div class="span-8"><div class="mapTitle">'.$mapTitle.'</div><div class="mapContent">'.$snip.'</div></div>';
$trimmed = trim($pass_to, " \r.");
?>
var point = new GLatLng('<?php echo $lat; $lat; ?>','<?php echo $long; $long; ?>');
var marker = createMarker(point,"<?php echo $mapTitle; $mapTitle; ?>", '<?php echo addslashes($trimmed); ?>');
map.addOverlay(marker);
Any other ideas out there on how I can pull this off?
I don't fully understand your exact problem, but the answer to the title of your question is quite simple:
$snip = str_replace('.', '', $snip); // remove dots
$snip = str_replace(' ', '', $snip); // remove spaces
$snip = str_replace("\t", '', $snip); // remove tabs
$snip = str_replace("\n", '', $snip); // remove new lines
$snip = str_replace("\r", '', $snip); // remove carriage returns
Or a all in one solution:
$snip = str_replace(array('.', ' ', "\n", "\t", "\r"), '', $snip);
You can also use regular expressions:
$snip = preg_replace('~[[:cntrl:]]~', '', $snip); // remove all control chars
$snip = preg_replace('~[.[:cntrl:]]~', '', $snip); // above + dots
$snip = preg_replace('~[.[:cntrl:][:space:]]~', '', $snip); // above + spaces
You'll still need to use addslashes() to output $snip inside Javascript.
I always use this to get rid of pesky carriage returns:
$string = str_replace("\r\n", "\n", $string); // windows -> unix
$string = str_replace("\r", "\n", $string); // remaining -> unix
if you need to remove new line symbols of all types (in utf8)
$dataWithoutCarrierReturn = preg_replace('/\R/', '', $inData);
Since you're putting this into Javascript, you'll need to escape it for javascript strings. addslashes() should do the trick.
Try JSON-encoding it, I always do that when I send data from PHP to Javascript. It solves most encoding issues, including newlines.
Use WP's own esc_js(), which will escape quotes and line breaks for JavaScript strings.
This was the only thing solution that worked for me:
$dataWithoutCarrierReturn = preg_replace('/[\x0D]/', '', $inData);

Categories