Move chunk of HTML with RegEx - html

What I am trying to do is find a chunk of HTML that has comments chunk!--/block--> and move it in its entirety right after header. The thing is that the comment always remains the same but the chunk varies through pages using find and replace in Dreamweaver. Here is a quick sample:
<!--header-->
<header>Hello</header>
<!--/header-->
This is where the chunk needs to be moved
<h1>Hello content</h1>
<p>lorem ipsum</p>
This is the chunk, it has a starting comment and ending one, I thought it might be used as a references for RegEx including everything inside.
<!--block-->
<p>hello world</p>
<!--/block-->

Ok. You didn't specify the language for reular expression but this PHP code does what you need I just wrote it and tested it. As a bonus I wrote the final result back to the source page.
First you have your original file, I called mine source.php
<!--header--> <header>SO HERE IS THE HEADER</header> <!--/header-->
<div>this is information that is above ID CARR, but will be below the div ID carr once php is done executing..</div>
<div id="carr"> Phasellus laoreet dolor magna, et tempor mi dictum eu. Aenean pellentesque vulputate tortor. Vestibulum odio velit, faucibus sed dui non, laoreet facilisis sem. Curabitur a magna ligula. Cras cursus vel dui placerat posuere. Donec ullamcorper risus eu lobortis dignissim. Nullam fermentum est diam, sed lacinia sapien ornare et. </div> <div>here is more informatin on the bottom</div>
Then you have another page called index.php that does what you want. In this example I am targeting the above.
<?php
$page_path = 'source.php';
$source = file_get_contents($page_path);
$regex = '#\<div id="carr">(.+?)\</div>#s';
preg_match($regex, $source, $matches);
$match = $matches[0];
$a = explode("</header>", $source);
//strip out what we found with regular expression
$first = str_replace($match, '', $source);
//append it to the place where you need it.
$final = str_replace('<!--/header-->', '<!--/header-->'.$match, $first);
echo $final;
$fp = fopen($page_path, 'w+');//w+ erases r+ point at begining of file.
fwrite($fp, $final);
fclose($fp);
?>

Related

Can't install Infinite Scroll

A few hours trying to implement Infinite Scroll in the blog. The goal is simple, the main page is too long, I want it to load gradually. The authors of the plugin have a perfectly working example, however, no matter what I do, in my case, the plugin doesn’t work properly. I guess I'm missing something.
If I understood correctly, then the plugin works like this: we create a common div and articles inside it. When entering a page, a person sees the first article, when he scrolls down to the next article, the page is enlarged and 2 article is already displayed, and so on. It seems to be what I am doing.
I tried to attach it through the link
<script src = "https://unpkg.com/infinite-scroll#3/dist/infinite-scroll.pkgd.min.js"> </ script>
Tried to upload file to server
<script src = "js/infinite-scroll.pkgd.min.js"> </script>
I tried to make the elements themselves through jQuery, JavaScript and just html, as suggested in the documentation, but all is unsuccessful.
This is a link to a very simple page of the site where I tried to implement it: https://dinarkino.ru/new. At the moment, all paragraphs are loaded at once, although each of them is wrapped in a separate
<article class = "post"> ... </ article>
I'll be very thankful for help!
Make sure you are running the page from http// address, infinite scroll will not work if you are running it from you local files. I set up a local environment using node, npm and express that looks like this ...
var express = require("express");
var PORT = 8080;
var app = express();
app.use(express.static("public"))
app.listen(PORT, function(){
console.log("App listening on PORT: " + PORT)
})
So my folder structure looks like this
.
├── node_modules
│
├── public
│ |── page1.html
│ |__ page2.html
│ |__ page3.html
│
├── server.js
│
Each section you want to load has to be its own .html file.
So the body page1.html would look like this. I changed your code to include
a div inside of the container to hold the posts and gave the data-infinite-scroll attribute to the div .posts-feed. Then I moved this
<div class="scroller-status">
<div class="loader-ellips infinite-scroll-request">
<span class="loader-ellips__dot"></span>
<span class="loader-ellips__dot"></span>
<span class="loader-ellips__dot"></span>
<span class="loader-ellips__dot"></span>
</div>
<p class="scroller-status__message infinite-scroll-last">End of content</p>
<p class="scroller-status__message infinite-scroll-error">No more pages to load</p>
</div>
<p class="pagination">
<a class="pagination__next" href="page2.html">Next page</a>
</p>
To be inside of container.
<body>
<div class="main">
<div class="container" >
<div class ="posts-feed" data-infinite-scroll='{ "path": ".pagination__next", "append": ".post", "status": ".scroller-status", "hideNav": ".pagination"}' >
<article class="post">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In hendrerit in sem eu elementum. Nam sagittis eleifend aliquam. Cras viverra, sapien vel auctor viverra, augue leo commodo ipsum, id euismod elit nisl id felis. Integer vitae mauris est. Cras vitae varius tortor. Nullam tristique ullamcorper imperdiet. Suspendisse potenti. Donec in elit felis. Donec eget nunc porttitor, lobortis lectus id, sagittis urna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam vitae ornare purus. Sed augue purus, cursus in malesuada non, interdum molestie massa. In interdum nisi at purus gravida rutrum. Praesent finibus lacus ac imperdiet tincidunt.</p>
<p><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></p>
</article>
</div>
<div class="scroller-status">
<div class="loader-ellips infinite-scroll-request">
<span class="loader-ellips__dot"></span>
<span class="loader-ellips__dot"></span>
<span class="loader-ellips__dot"></span>
<span class="loader-ellips__dot"></span>
</div>
<p class="scroller-status__message infinite-scroll-last">End of content</p>
<p class="scroller-status__message infinite-scroll-error">No more pages to load</p>
</div>
<p class="pagination">
<a class="pagination__next" href="page2.html">Next page</a>
</p>
</div>
</div>
</body>
Notice how at the end there is a piece that looks like this
<p class="pagination">
<a class="pagination__next" href="page2.html">Next page</a>
</p>
This is telling infinite scroll what to load next in href. This here will then load the contents from a separate file called page2.html
Then one page2.html that same section should read
<p class="pagination">
<a class="pagination__next" href="page3.html">Next page</a>
</p>
so that page3.html contents are loaded.

How to shrink the font size of numbers in parentheses?

I have an essay with sidenotes. The page has two columns, one for the essay, another for the sidenotes. If a sentence has a sidenote, it is followed by a number in parentheses. The number is the sidenote number. For example: Essay: The sun circles the earth. (1) Sidenote: (1) Wrong!
My goal is to make all the numbers+parentheses smaller. I assume there is a simple CSS solution.
I should add that there are 80 different notes, hence my need for a simple, time-saving solution. Is there one that would allow me to say, "for every (n) where n is a number, make font 8pt"?
If you're looking for a pure CSS solution, you're out of luck. CSS is unable to parse text and manipulate the DOM—that is the work of JavaScript. If you are able to manually change the markup, you can wrap your citations, e.g. (1), with a semantic element, such as <sup>(1)</sup> if you want it to appear as superscript, or <span>(1)</span> if you want to style it otherwise. Given that you wanted Wikipedia-style citations, the former would be the way to go.
However, if you want the browser to parse your digits in parenthesis on-the-go, CSS alone is insufficient—you will have to use JS. As mentioned before, the best way to find such citations is to look for a format, for example, the following regex pattern will probably suffice: \(\d+\). However, it again depends on how you want them to be match. If you do not want them to match erroneously to normal bracketed numbers, such as within sentences, or in bulleted points, you will have to include a negated whitespace character before it: [^\s]\(\d+\).
Here is a simple example with JS+CSS combined:
$(function() {
$('p').each(function() {
$(this).html($(this).html().replace(/[^\s](\(\d+\))/gi,'<sup>$1</sup>'));
});
});
sup {
color: blue;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dapibus interdum ullamcorper, for example: (1) Suspendisse semper mattis ante, et efficitur justo tempor in; (2) Cras iaculis, magna a bibendum porta, diam massa ornare nisi, eget finibus sapien enim non elit; (3) Pellentesque ut ultrices libero.</p>
<p>Donec non velit et ante vestibulum maximus(1). Phasellus ac interdum nisi, eu iaculis massa. Proin vel sem est. Morbi euismod massa eu commodo efficitur. Phasellus vitae leo euismod, pretium turpis sit amet, bibendum elit(2). In efficitur id metus ullamcorper tristique. Integer et felis in felis suscipit tincidunt nec nec lectus.</p>
<p>Vestibulum mollis, magna sodales maximus faucibus, leo risus pretium libero, at placerat urna eros et nisl(3). Nunc cursus enim diam, in accumsan augue faucibus vel. Integer feugiat egestas lectus eu blandit. Donec ac neque turpis. Donec imperdiet feugiat purus, a congue dui convallis ut(4). Sed scelerisque ac massa non feugiat. Aliquam erat volutpat. Donec vestibulum odio id pulvinar elementum. Ut laoreet massa ac nibh pulvinar, id consequat tellus malesuada(5). Fusce porta purus diam, in luctus odio laoreet quis. Quisque condimentum condimentum felis sed rutrum. Aenean pellentesque felis in posuere efficitur. Mauris tristique ultricies massa at euismod.</p>
If you want a CSS solution, you could use the following:
HTML
<b>Essay:</b> The sun circles the earth. <span class="sidenote-number">(1)</span>
<b>Sidenote:</b> <span class="sidenote-number">(1)</span> Wrong!
CSS
.sidenote-number {
font-size: 10px;
}
The style in the sidenote-number class will be applied to the text inside of the spans.
Demo
What you may be looking for is the HTML <sup> (or <sub>) notation.
They stand for subscript and superscript respectively. The sub tag will allow you to create 'Wikipedia like' small numbers.
Example of superscript [1] (<sup>[1]</sup>)
Example of subscript [1] (<sub>[1]</sub>)
Here is a solution based on my comment. It amounts to a trivialized reference management system like bibtex.
Comment:
Maybe what you really want, is to use
every place you want a numbered side note, and then use javascript to
go through and automatically number and format them. That would be a
tradeoff between having to declare the span classes but not having to
keep track of your sidenote numbers.
This way, instead of hard-coding the side note numbers, you could add, remove or rearrange the notations, and they would still be automatically numbered properly.
http://jsfiddle.net/abalter/z43gxsfy/
html:
<h1>Cascading Style Sheets (CSS)</h1>
<p>Cascading Style Sheets (CSS) is a style sheet language used for describing the
look and formatting of a document written in a markup
language <span class="sidenote" data-source="src1"></span>.
Although most often used to change the style of web pages and user
interfaces written in HTML and XHTML, the language can be applied to
any kind of XML document, including plain XML, SVG and XUL. Along with
HTML and JavaScript, CSS is a cornerstone technology used by most websites
to create visually engaging webpages, user interfaces for web applications,
and user interfaces for many mobile applications <span class="sidenote" data-source="src2"></span>.</p>
<h3>References</h3>
<ul id='references'></ul>
CSS:
#references {
list-style: none;
}
.sidenote {
font-size: 0.8em;
}
Javascript:
var sources = {
src1: "Article by so and so in such and such",
src2: "Book by someone"
};
var sidenotes = $('.sidenote');
$('.sidenote').each(function(index){
$(this).html('(' + (index+1) + ')');
$('#references').append($('<li>').html("(" + (index+1) + ") " + sources[$(this).data('source')]));
});
Untested regex/javascript/jquery solution:
$(document).ready(function()
{
walk(document.body);
});
//Iterate through every part of the page
function walk(node)
{
// I stole this function from here:
// http://is.gd/mwZp7E
var child, next;
switch (node.nodeType)
{
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while(child)
{
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
check(node);
break;
}
//Check if the text node contains parentheses.
function check(node)
{
var v = textNode.nodeValue;
var res = v.match(/\(*.\)/g); //Match anything inside of parentheses
if(res)
{
v.style.fontSize = "8px"; //Not sure if that part would actually work
}
textNode.nodeValue = v;
}

Replace custom tags with html using preg_replace_callback

Am trying to do a replacement of customized tags with html tags in my website as follows:
[block-2] "Donec volutpat nibh sit amet libero ornare non laoreet arcu luctus. Donec id arcu quis mauris". [/block-2]
If the above [block] tag is encountered, it should be replaced by some html tags (using regexp), specifically:
<blockquote class="tm-style2"><span>
"Donec volutpat nibh sit amet libero ornare non laoreet arcu luctus. Donec id arcu quis mauris".
</span></blockquote>
I have tried the following but is not working. Please help:
$article_text = preg_replace_callback(
"(\[block-([0-9]+)\](.+)\[\/block-([0-9]+)\])",
create_function('$p','return "<blockquote class=\"tm-style".$p[1]."\"><span>".$p[2]."</span></blockquote>";'), $article_text);
You don't actually need to use preg_replace_callback function, just preg_replace would be fine.
\[(block-([0-9]+))\](.+?)\[\/\1\]
Then replace the matched characters with
<blockquote class="tm-style\2"><span>\n\3\n</span></blockquote>
DEMO
$re = "~\\[(block-([0-9]+))\\](.+?)\\[\\/\\1\\]~m";
$str = "[block-2] \"Donec volutpat nibh sit amet libero ornare non laoreet arcu luctus. Donec id arcu quis mauris\". [/block-2]";
$subst = '<blockquote class="tm-style\2"><span>'."\n".'\3'."\n".'</span></blockquote>';
$result = preg_replace($re, $subst, $str);
echo $result;
Output:
<blockquote class="tm-style2"><span>
"Donec volutpat nibh sit amet libero ornare non laoreet arcu luctus. Donec id arcu quis mauris".
</span></blockquote>
You need to escape closing tag's backslash in your pattern ...[\/block....
So full pattern is (\[block-([0-9]+)\](.+)\[\/block-([0-9]+)\])

How to insert a piece of HTML code in xml Word document (and not die trying)

this is the scenario
I have a Word document ( .docx ) which i want to convert in a template, saving it as a "XML Word 2003" file. Inside the document content, i put a custom tag named {MY_CONTENT} which will be replaced with HTML code.
When I generate a word document like this, it didn't open properly. This is the HTML code i'm trying to insert into the Word Xml document:
<div style='text-align: center;'>
<b><font size='3'>Contract</font></b>
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin quis justo elementum,
vehicula ante vel, facilisis ante. Aenean dolor lectus, cursus in mattis sed, ullamcorper ut quam.
Quisque fringilla erat sit amet blandit euismod. Integer nec odio vel erat molestie fringilla.
Aliquam tempor ac urna vitae convallis. Praesent mattis massa eget lectus mattis,
non imperdiet ipsum suscipit. Phasellus gravida eros turpis, et faucibus libero gravida
non.
Aliquam ultricies nisl eget magna tincidunt tincidunt. Proin feugiat interdum nibh nec rutrum.
In hac habitasse platea dictumst. Etiam ac condimentum nisl, et volutpat mauris.
Mauris erat dui, aliquam ut urna vel, euismod placerat est.
<font size='3'></font>
</div>
I tried to "htmlencode" the html code above, but still the document is not opened property.
If it was possible to "traslate" a HTML piece of code into Word xml tags, i think it could be resolved.
... or is there a way to display the html code into the word xml document, without converting it or applying sorcery ?
Thanx in advance.
Thanx for your kind comments. I stored them in my PKDB ( personal knowledge database ) :) for further uses.
Finally, I decided to use ITEXTSHARP library to generate the document, because it gives me the tools to insert HTML code without formatting isues.
I inserted an image template as background, wrote the HTML code, and that's all.
Hope this piece of code to be useful for any person
This is the code
string pathImagenPlantilla = Server.MapPath(<path_of_the_image_template>);
//generar el pdf al vuelo
string filenamePDF = "Your_Document_Name.pdf";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + filenamePDF);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//load the image template
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(pathImagenPlantilla);
//define your HTML code
StringBuilder strTextoHTML = new StringBuilder();
strTextoHTML.Append("<html>");
strTextoHTML.Append("<body>");
strTextoHTML.Append(<your HTML CODE right here>);
strTextoHTML.Append("</body>");
strTextoHTML.Append("</html>");
// margins, in milimeters
float margenIzquierdo = 25;
float margenDerecho = 25 ;
float margenSuperior = 25 ;
float margenInferior = 10 ;
Document pdfDoc = new Document(PageSize.A4, margenIzquierdo, margenDerecho, margenSuperior, margenInferior);
//Adjust the size of image template , to the screen size
float pageWidth = pdfDoc.PageSize.Width - (margenIzquierdo + margenDerecho);
float pageHeight = pdfDoc.PageSize.Height - (margenInferior + margenSuperior);
jpg.SetAbsolutePosition(margenIzquierdo, margenInferior);
jpg.ScaleToFit(pageWidth, pageHeight);
//If you want to choose image as background then,
jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
pdfDoc.NewPage();
//add image template
pdfDoc.Add(jpg);
//add html code
foreach (IElement E in HTMLWorker.ParseToList(new StringReader(strTextoHTML.ToString()), new StyleSheet()))
{
pdfDoc.Add(E);
}
//close doc and display/download
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
Regards,

Actionscript 3 TextField height

I need to set the text field autosize property to NONE to ensure that HTML links do not jump on rollovers.
However, when I do this, how can I set the textfield height property to show all of the text without scrolling?
I have tried the following but for a reason I cannot figure out, it's squishing the height of my text:
htmlTextField.autoSize = TextFieldAutoSize.LEFT;
htmlTextField.htmlText = htmlText;
var recordedHeight:Number = htmlTextField.textHeight;
htmlTextField.autoSize = TextFieldAutoSize.NONE;
htmlTextField.height = recordedHeight + htmlTextField.getTextFormat().leading + 1;
TextFields have a 2px gutter all the way around so this may be tripping you up.
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
[SWF(frameRate="30", backgroundColor="#FFFFFF", width="500", height="500")]
public class TextfieldHeight extends Sprite
{
public function TextfieldHeight()
{
var textFormat:TextFormat = new TextFormat();
textFormat.size = 11;
textFormat.font = "Georgia";
var htmlTextField:TextField = new TextField();
htmlTextField.setTextFormat( textFormat );
htmlTextField.width = 250;
htmlTextField.border = true;
htmlTextField.wordWrap = true;
htmlTextField.autoSize = TextFieldAutoSize.NONE;
htmlTextField.htmlText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales, eros at convallis viverra, risus mauris euismod tortor, ac imperdiet sem augue vitae risus. Morbi ut sem neque. Vestibulum accumsan posuere augue, eu consectetur nibh porttitor eget. Sed suscipit sodales dui id pharetra. Vivamus quis hendrerit lectus. Vivamus interdum, felis a convallis dictum, libero erat aliquet massa, non placerat neque augue quis lacus. Aliquam viverra sem ultrices leo lacinia eu dignissim dolor ullamcorper. Etiam ullamcorper tincidunt velit, a vulputate sapien consequat quis.';
htmlTextField.height = htmlTextField.textHeight + 4;
this.addChild( htmlTextField );
}
}
}
If you go here and read.
you will see.
Returns flash.text:TextFormat — The TextFormat object that represents
the formatting properties for the specified text.
Now if you look at TextFormat You will see the defaults are all pretty much 0
I ran into this issue a long time ago and the only work around I found was to select some text then grab defaultTextFormat and then deselect the text.
I am sure there is another method to do this but like I said it was my hack-a-round.