Consider:
<?php
define('my_const', 100);
echo <<<MYECHO
<p>The value of my_const is {my_const}.</p>
MYECHO;
?>
If I put a variable inside the braces, it prints out. But not the constant. How can I do it?
You can also approach the problem by assigning the value of the constant to a variable.
Personally I do it that way because if you have lots of constants in your string then your sprintf() call can be quite messy. It's also then harder to scan through the string and see what is doing what. Plus, by assigning the variables individually, you can see what is taking on what value.
An example would be:
$const = CONST;
$variable = VARIABLE;
$foo = (new Foo)->setFooProperty(12)->getFooProperty();
$bar = (123 - 456) * 10;
$ten = 1 + 2 + 1 + (5 - 4);
<<<EOD
Lorem ipsum dolor sit amet, **$variable** adipiscing elit.
Duis gravida aliquet dolor quis gravida.
Nullam viverra urna a velit laoreet, et ultrices purus condimentum.
Ut risus tortor, facilisis sed porta eget, semper a augue.
Sed adipiscing erat non sapien commodo volutpat.
Vestibulum nec lectus sed elit dictum accumsan vel adipiscing libero.
**$const** vehicula molestie sapien.
Ut fermentum quis risus ut pellentesque.
Proin in dignissim erat, eget molestie lorem. Mauris pretium aliquam eleifend.
**$foo** vitae sagittis dolor, quis sollicitudin leo.
Etiam congue odio sit amet sodales aliquet.
Etiam elementum auctor tellus, quis pharetra leo congue at. Maecenas sit amet ultricies neque.
Nulla luctus enim libero, eget elementum tellus suscipit eu.
Suspendisse tincidunt arcu at arcu molestie, a consequat velit elementum.
Ut et libero purus. Sed et magna vel elit luctus rhoncus.
Praesent dapibus consectetur tortor, vel **$bar** mauris ultrices id.
Mauris pulvinar nulla vitae ligula iaculis ornare.
Praesent posuere scelerisque ligula, id tincidunt metus sodales congue.
Curabitur lectus urna, porta sed molestie ut, mollis vitae libero.
Vivamus vulputate congue **$ten**.
EOD;
Use sprintf()
define('my_const', 100);
$string = <<< heredoc
<p>The value of my_const is %s.</p>
heredoc;
$string = sprintf($string, my_const);
Here is an little trick to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls. It uses the fact that a function name can be assigned to a variable and then called within heredoc:
<?php
// Declare a simple function
function _placeholder($val) { return $val; }
// And assign it to something short and sweet
$_ = '_placeholder';
// Or optionally for php version >= 5.3
// Use a closure (anomynous function) like so:
$_ = function ($val){return $val;};
// Our test values
define('abc', 'def');
define('ghi', 3);
$a = 1;
$b = 2;
function add($a, $b) { return $a+$b; }
// Usage
echo "b4 {$_(1+2)} after\n"; // Outputs 'b4 3 after'
echo "b4 {$_(abc)} after\n"; // Outputs 'b4 def after'
echo "b4 {$_(add($a, $b)+ghi*2)} after\n"; // Outputs 'b4 9 after'
$text = <<<MYEND
Now the same in heredoc:
b4 {$_(1+2)} after
b4 {$_(abc)} after
b4 {$_(add($a, $b)+ghi*2)} after
MYEND;
echo $text;
You can also use the get_defined_constants function. It puts back all currently defined constants in an array, which you can use in your HEREDOC string:
// Let's say there is FOO and BAR defined
$const = get_defined_constants();
$meta = <<< EOF
my awesome string with "{$const['FOO']}" and "{$const['BAR']}" constants
EOF;
You may use the "constant" function.
for example:
<?php
define('CONST1', 100);
define('CONST2', 200);
$C= 'constant';
echo <<<MYECHO
<p>The value of CONST1 is: {$C('CONST1')},
and CONST2 is:{$C('CONST2')}.</p>
MYECHO;
?>
Put your defined variable into simple variable and use include it in heredoc just as in following example:
<?php
define('my_const', 100);
$variable = my_const;
echo <<<MYECHO
<p>The value of my_const is {$variable}.</p>
MYECHO;
?>
Not everybody will like the use of shorthand echo tags, but this is still an option:
<?php
define('my_const', 100);
?>
<p>The value of my_const is <?= my_const ?>.</p>
Related
we are making a report in PDF by using FPDF.
we are getting text in our pdf report by using $pdf->WriteHTML(utf8_decode($main));, now we want to justify text in report, but we are not able to do the same.
Please suggest solution for this.
Thanks!
This tutorial shows you how to justify with WriteHTML.
http://www.fpdf.org/en/script/script41.php
demo
Code:
<?php
require('fpdf.php');
class PDF_HTML extends FPDF
{
var $B=0;
var $I=0;
var $U=0;
var $HREF='';
var $ALIGN='';
function WriteHTML($html)
{
//HTML parser
$html=str_replace("\n",' ',$html);
$a=preg_split('/<(.*)>/U',$html,-1,PREG_SPLIT_DELIM_CAPTURE);
foreach($a as $i=>$e)
{
if($i%2==0)
{
//Text
if($this->HREF)
$this->PutLink($this->HREF,$e);
elseif($this->ALIGN=='center')
$this->Cell(0,5,$e,0,1,'C');
else
$this->Write(5,$e);
}
else
{
//Tag
if($e[0]=='/')
$this->CloseTag(strtoupper(substr($e,1)));
else
{
//Extract properties
$a2=explode(' ',$e);
$tag=strtoupper(array_shift($a2));
$prop=array();
foreach($a2 as $v)
{
if(preg_match('/([^=]*)=["\']?([^"\']*)/',$v,$a3))
$prop[strtoupper($a3[1])]=$a3[2];
}
$this->OpenTag($tag,$prop);
}
}
}
}
function OpenTag($tag,$prop)
{
//Opening tag
if($tag=='B' || $tag=='I' || $tag=='U')
$this->SetStyle($tag,true);
if($tag=='A')
$this->HREF=$prop['HREF'];
if($tag=='BR')
$this->Ln(5);
if($tag=='P')
$this->ALIGN=$prop['ALIGN'];
if($tag=='HR')
{
if( !empty($prop['WIDTH']) )
$Width = $prop['WIDTH'];
else
$Width = $this->w - $this->lMargin-$this->rMargin;
$this->Ln(2);
$x = $this->GetX();
$y = $this->GetY();
$this->SetLineWidth(0.4);
$this->Line($x,$y,$x+$Width,$y);
$this->SetLineWidth(0.2);
$this->Ln(2);
}
}
function CloseTag($tag)
{
//Closing tag
if($tag=='B' || $tag=='I' || $tag=='U')
$this->SetStyle($tag,false);
if($tag=='A')
$this->HREF='';
if($tag=='P')
$this->ALIGN='';
}
function SetStyle($tag,$enable)
{
//Modify style and select corresponding font
$this->$tag+=($enable ? 1 : -1);
$style='';
foreach(array('B','I','U') as $s)
if($this->$s>0)
$style.=$s;
$this->SetFont('',$style);
}
function PutLink($URL,$txt)
{
//Put a hyperlink
$this->SetTextColor(0,0,255);
$this->SetStyle('U',true);
$this->Write(5,$txt,$URL);
$this->SetStyle('U',false);
$this->SetTextColor(0);
}
}
?>
Usage:
<?php
require('WriteHTML.php');
$pdf=new PDF_HTML();
$pdf->AddPage();
$pdf->SetFont('Arial');
$pdf->WriteHTML('You can<br><p align="center">center a line</p>and add a horizontal rule:<br><hr>');
$pdf->Output();
?>
Use Tag-based formatting script. I don't use class PDF_HTML, that way only "dirty" solution:
<?php
require('fpdf.php');
class PDF_HTML extends FPDF {
...
elseif($this->ALIGN == 'center')
$this->Cell(0,5,$e,0,1,'C');
elseif($this->ALIGN == 'justify') {
//$this->SetStyle("p","arial","N",7,"0,0,0"); //TODO
$this->WriteTag(180, 11, $e, 0, "J");// TODO parameters
} else
...
}
class PDF_WriteTag extends PDF_HTML {
...
}
ob_start(); // TODO delete after correcting any errors (only for demo)
$pdf = new PDF_WriteTag();
$pdf->AddPage();
$pdf->SetFont('Arial');
$pdf->WriteHTML('You can<br><p align="center">center a line</p>and add a horizontal rule:<br><hr>');
$pdf->WriteHTML('You can<br><p align="justify">Et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque vitae erat. Vivamus porttitor cursus lacus. Pellentesque tellus. Nunc aliquam interdum felis. Nulla imperdiet leo. Mauris hendrerit, sem at mollis pharetra, leo sapien pretium elit, a faucibus sapien dolor vel pede. Vestibulum et enim ut nulla sollicitudin adipiscing. Suspendisse malesuada venenatis mauris. Curabitur ornare mollis velit. Sed vitae metus. Morbi posuere mi id odio. Donec elit sem, tempor at, pharetra eu, sodales sit amet, elitCurabitur urna tellus, aliquam vitae, ultrices eget, vehicula nec, diam. Integer elementum, felis non faucibus euismod, erat massa dictum eros, eu ornare ligula tortor et mauris. Cras molestie.
</p>and add a horizontal rule:<br><hr>');
ob_clean(); //TODO delete after correcting any errors
$pdf->Output();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have a database field with large text. If there is a tag inside <!-- new page --> I want to paginate by that tag.
What I'm trying to do is something like WordPress has, when you insert a tag such as <!-- new page --> I want to create a new page.
Say I have this text from a database
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque elementum magna in nulla ultrices, eu pulvinar nulla auctor. Praesent auctor ut dui vitae feugiat.
<!-- new page -->
Sed risus nisl, tristique sed tristique et, auctor eu augue. In hac habitasse platea dictumst. Fusce a ipsum ligula. Aliquam vestibulum ligula ut ligula porta gravida. Curabitur tincidunt a est vitae eleifend. Duis ullamcorper nunc sapien, quis molestie tellus ornare vel. Nullam in mi eros.
How would I make the second paragraph appear on a new page?
Something like this http://en.support.wordpress.com/splitting-content/nextpage/
i hope my code will be helpfull :
<?php
//in this example :
//first you have to create a database with name : blog
// create table : article (id as primary key, name , content)
// here we supposed that in the content you have your tags <!-- new page -->
// also i supposed the name of this file as : pagination.php
//Getting the id of article:
//=========================
if(isset($_GET['id']))
$id_article = $_GET['id'];
else
$id_article = 1;
//Connexion to database :
//======================
$user="root";
$pass="root";
$db="blog";
$host="localhost";
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass, $pdo_options);
$bdd->query("SET NAMES 'utf8'");
$response = $bdd->query('SELECT * FROM articles WHERE id='.$id_article);
$tab_content = array();
$data = $response->fetch()
echo'<div >';
$tab_content = explode('<!-- new page -->',$data['content']);
$count_pages = count($tab_content);
if($count_pages){
//in the case that you have somme tags :
//=====================================
echo $tab_content[$page];
echo '<br>';
for($i=1;$i<$count_pages;$i++)
echo ''.$i.' ';
}
else{
//if no tags '<!-- new page -->' in your content:
//===============================================
echo $data['content'];
}
echo '</div>';
$response->closeCursor();
?>
I'm not sure of the terminology so I apologize ahead of time.
I'm trying to create a PHP template engine that will query a string for <ZONE header> and </ZONE header> and it will pull everything in between and then run a php function to see if the header exists. If the header exists it will display what was in between, and if the header does not exists it will remove what was in between.
Here's an example:
$string = "
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<ZONE header><img src="images/header.jpg" /></ZONE header>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
";
The function would ideally remove <ZONE header><img src="images/header.jpg" /></ZONE header> then it will run the php function I've created header() which checks to see if the "header" exists in the database, and if it does, it will display everything inside <ZONE header></ZONE header> and if it doesn't it will remove it from the string.
If "header" exists:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<img src="images/header.jpg" />
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
If "header" does not exist:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
Here is what I was working with but got stuck:
preg_match_all("|\<ZONE_header>(.*)\<\/ZONE_header>|isU", $string, $zone, PREG_SET_ORDER);
if (isset($zone) && is_array($zone)) {
foreach ($zone as $key => $zoneArray) {
if ($key == 0) {
$html = $zoneArray[1];
if ($html != "") {
if (header() != "") {
$html = str_replace($zoneArray[0], NULL, $html);
}
}
}
}
}
echo $html;
Any ideas, thoughts, suggestions?
Thank you for any and all help!
Note that I replace your header() function with get_header().
$string = preg_replace_callback('/<ZONE header>(.+)<\/ZONE header>/', 'replace_header', $string);
function replace_header($matches) {
return get_header() ? $matches[1] : '';
}
See documentation for preg_replace_callback.
Like this ?
$string = '
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<ZONE header><img src="images/header.jpg" /></ZONE header>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
';
$pattern="#<ZONE header[^>]*>(.+)</ZONE header>#iU";
preg_match_all($pattern, $string, $matches);
if (strlen($matches[0][0])==0){
$string=strip_tags($string,"<p>");
}
else{
$string=strip_tags($string,"<p><img>");
}
echo $string;
How would I use PHP's preg_replace() to return only the value inside the <h1> in the following string (it's HTML text loaded in a variable called $html):
<h1>I'm Header</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis.</p>
<p>Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
I've tried this: preg_replace('#<h1>([.*])</h1>.*#', '$1', $html), but to no avail. Am I regex-ing this correctly? And is there a better PHP function that I should be using instead of preg_replace?
Here is how you do it using preg_replace:
$header = preg_replace('/<h1>(.*)<\/h1>.*/iU', '$1', $html);
You can also use preg_match:
$matches = array();
preg_match('/<h1>(.*)</h1>.*/iU', $html, $matches);
print_r($matches);
([.*]) means dot OR astersk
What you need is (.*?), which means any amount of any characters ungreedy
or
([^<]*) - which means any amount of any characters but not <
I am working with html document generated from Micrsoft Word 2007/2010. Besides generating incredibly dirty html, word also has the tendency of using both block and inline style. I am looking for a php library would merge block into already existing inline style element.
Edit
The goal is to construct a html block preserve the original formatting and editable in WYSIWYG editor like tinyMCE
Example
If the original html is:
<html>
<head>
<style>
.normaltext {color:black;font-weight:normal;font-size:10pt}
.important {color:red;font-weight:bold;font-size:11pt}
</style>
<body>
<p class="normaltext" style="font-family:arial">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span class="important">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span class="important" style="color:green">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Should become:
<html>
<head>
<body>
<p style="font-family:arial;color:black;font-weight:normal;font-size:10pt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span style="color:red;font-weight:bold;font-size:11pt">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span style="color:green;font-weight:bold;font-size:11pt">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Check out:
http://inlinestyler.torchboxapps.com/
http://premailer.dialect.ca/
http://www.pelagodesign.com/sidecar/emogrifier/
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
http://beaker.mailchimp.com/inline-css
http://burrowscode.wordpress.com/2011/02/19/emailify-internal-stylesheets-to-inline-styles/
https://github.com/crcn/emailify
https://github.com/peterbe/premailer
Porting code from either of the sources to PHP, or using any of the available APIs should do the trick of getting your CSS styling inline.
See the CssToInlineStyles project which does exactly what you want.
No, but try this instead, copying and pasting from word into http://ckeditor.com/ or tinymce, etc does clean it up A LOT, thought it's still not perfect it will get you much closer.
I finally managed to get it to work. The code is based off of
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
with once simple change:
Moving the line
// add new properties into the list
foreach($rule['properties'] as $key => $value) $properties[$key] = $value;
up to the begining of the loop, right after where $properties is declared.
To make this work for WordPress however, one additional change is needed. DomDocument replace &nbps; from the document with blanks, which breaks WordPress update statement and lead to cotent being cut off. Please refer to my other question for the solution:
DOMDocument->saveHTML() converting to space
This problem is detailed in https://wordpress.stackexchange.com/questions/48692/post-content-getting-cut-off-on-blank-space-on-wpdb-update. If you know why this is happening for WordPress, please post your answer there as I would very much like to find out why it is happening.