Idiomatic HTML generation in PHP - php

In a separate question here on StackOverflow (PHP library for HTML tag generation) I asked if there is a popular or standard HTML tag library for PHP.
A couple of comments showed up questioning the purpose of such a library.
Here's a bit of code from the highly acclaimed book "PHP and MySQL Web Development 4th Edition" by Luke Welling and Laura Thomson:
echo "<td width = \"".$width."%\">
<a href=\"".$url."\">
<img src=\"s-logo.gif\" alt=\"".$name."\" border=\"0\" /></a>
<span class=\"menu\">".$name."</span>
</td>";
I thought all the escaping and concatenating looked a little messy, so I cooked up an HTML generation library. The above looks like this using the library:
return td(array('width' => $width . '%'),
a(array('href' => $url),
img(array('src' => 's-logo.gif', 'alt' => $name, 'border' => 0))),
a(array('href' => $url), span(array('class' => 'menu'), $name)));
My question is (and keep in mind, I'm a php newb), what's the idiomatic way to write the above? Is there a cleaner way to write the book example?

You can use PHP heredoc syntax
<?php
$width=10;
$url="www.google.com";
$name="stackoverflow";
echo <<<EOT
<td width = "$width">
<a href="$url">
<img src="s-logo.gif" alt="$name" border="0" /></a>
<span class="menu">$name</span>
</td>
EOT;
?>
For more information refer Php Manual

Cleaner - definitely, with heredoc:
echo <<<HTML
<td width="{$width}%">
<img src="s-logo.gif" alt="{$name}" border="0" />
<span class="menu">{$name}</span>
</td>
HTML;

Related

Regex in PHP for Extract and Reformatting

I am working on a project with facebook instant article. I would like to do automatic conversion through PHP script but I have problem with reformatting this code
[caption id="attachment_15737" align="aligncenter" width="1024"]<img class="wp-image-15737 size-full" title="bathroom counter decor" src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg" alt="bathroom counter decor" width="1024" height="768" /> © ivote[/caption]
into this code
<figure><img class="wp-image-15737 size-full" title="bathroom counter decor" src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg" alt="bathroom counter decor" width="1024" height="768" /><figcaption>© ivote</figcaption></figure>
Can anyone help me out with this problem?
I would really appreciate any help. Thank you.
You should probably consider using some sort of formal parser to handle this problem in the general case. That being said, if you are willing to accept the risks with just using a single regex, then consider matching with the finding pattern, and replacing with the pattern after it:
/\[caption [^<]*(<img[^>]*>)\s*([^[]*)\[\/caption\]/
<figure>$1<figcaption>$2</figcaption></figure>
Here is the code:
$input = "[caption id=\"attachment_15737\" align=\"aligncenter\" width=\"1024\"]<img class=\"wp-image-15737 size-full\" title=\"bathroom counter decor\" src=\"https://roohome.com/wp-content/uploads/2017/11/ivote.jpg\" alt=\"bathroom counter decor\" width=\"1024\" height=\"768\" /> © ivote[/caption]";
$after = preg_replace('/\[caption [^<]*(<img[^>]*>)\s*([^[]*)\[\/caption\]/', '<figure>$1<figcaption>$2</figcaption></figure>', $input);
echo $after;
This outputs the following HTML:
<figure><img class="wp-image-15737 size-full" title="bathroom counter decor"
src="https://roohome.com/wp-content/uploads/2017/11/ivote.jpg"
alt="bathroom counter decor" width="1024" height="768" />
<figcaption>© ivote</figcaption>
</figure>
Demo

get image src from HTML with regex

I have HTML like
<td class="td_scheda_modello_dati">
<img src="/webapp/safilo/gen_img/p_verde.gif" width="15" height="15" alt="" border="0">
</td>
I want to extract the img src from this HTML using preg_match_all().
I have done this
preg_match_all('#<td class=td_scheda_modello_dati>(.*)<td>#',$detail,$detailsav);
It should give the whole img tag.But it doesn't give me the img tag. So what changes should be done to get the specific value?
Long story short: ideone
You should not use Regex, but instead an HTML parser. Here's how.
<?php
$html = '<img src="/webapp/safilo/gen_img/p_verde.gif" width="15" height="15" alt="" border="0">';
$xpath = new DOMXPath(#DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/#src)");
echo $src;
?>
Try this code.
$html_text = '<td class="td_scheda_modello_dati">
<img src="/webapp/safilo/gen_img/p_verde.gif" width="15" height="15" alt="" border="0"></td>';
preg_match( '/src="([^"]*)"/i', $html_text , $res_array ) ;
print_r($res_array);
Try using the s modifier after your regex. The default behavior for the dot character is not to match newlines (which your example has).
Something like:
preg_match_all('#<td class=td_scheda_modello_dati>(.*)</td>#s',$detail,$detailsav);
Should do the trick.
It's worth reading up a bit on modifiers, the more you do with regex the more useful they become.
http://php.net/manual/en/reference.pcre.pattern.modifiers.php
Edit: also, just realized that the code posted was missing a closing td tag (it was <td> instead of </td>). Fixed my example to reflect that.
Try this: <img[^>]*src="([^"]*/gen_img/p_verde.gif)"

How to get content from a div using regex

I have string like :
<div class="fck_detail">
<table align="center" border="0" cellpadding="3" cellspacing="0" class="tplCaption" width="1">
<tbody>
<tr><td>
<img alt="nole-1375196668_500x0.jpg" src="http://l.f1.img.vnexpress.net/2013/07/30/nole-1375196668_500x0.jpg" width="500">
</td></tr>
<tr><td class="Image">
Djokovic hậm hực với các đàn anh. Ảnh: <em>Livetennisguide.</em>
</td></tr>
</tbody>
</table>
<p>Riêng với Andy Murray, ...</p>
<p style="text-align:right;"><strong>Anh Hào</strong></p>
</div>
I want to get content . How to write this pattern using preg_match. Please help me
If there are no other HTML tags inside the div, then this regex should work:
$v = '<div class="fck_detail">Some content here</div>';
$regex = '#<div class="fck_detail">([^<]*)</div>#';
preg_match($regex, $v, $matches);
echo $matches[1];
The actual regex here is <div class="fck_detail">([^<]*)</div>. Regexes used in PHP also need to be surrounded by some other character that doesn't occur in the regex (I used #).
However, if what you're parsing is arbitrary HTML provided by the user, then preg_match simply can't do this. Full-fledged HTML parsing is beyond the ability of any regex, and that's what you'll need if you're parsing the output of a full-fledged HTML editor.

calling a php img string in html

Pretty straight forward simple question, can you open a php code block to call image information in html? I don't think I phrased that right. Here is my code:
<img src="../inventory_images/' . <?php echo $item_number; ?> . '.jpg" width="150" height="150" border="2" />
This code is within the tags
I'm just trying to post a photo using the $item_number variable (which is also the name of the image file i.e. $item_number = T3144 and the image file is name T3144.jpg ). Also if there is a better way to accomplish this suggestions are happily accepted. Sorry to take up bandwidth with such a remedial question but for some reason I can't seem to answer this question in research. Thanks for taking the time everyone.
Your code is wrong, try:
<img src="../inventory_images/<?php echo $item_number;?>.jpg" width="150" height="150" border="2" />
with what you have it looks like the code you had would print
src="../inventory_images/' . whateveritem_numberis . '.jpg"
Yes that is perfectly fine, but make sure that this code is in a file that ends with .php or it will not get parsed by PHP. Also, you need to take out the single quotes and periods:
<img src="../inventory_images/<?php echo $item_number; ?>.jpg" width="150" height="150" border="2" />
Unless the above HTML is in an echo statement, you need to change it to this:
<img src="../inventory_images/<?php echo $item_number; ?>.jpg" width="150" height="150" border="2" />
That will in-turn look like this:
<img src="../inventory_images/T3144.jpg" width="150" height="150" border="2" />
Of course, that is going off of your example where $item_number = 'T3144';.
The single quotes and periods are used for concatenating variables inside of strings.

Creating pattern to php preg_match_all

I'm using preg_match_all() and my problem is that I can't create the pattern that I want. Example of source text:
<td align='left'>
<span style='font-size: 13px; font-family: Verdana;'><span>
</td>
<td>
<a style='color: #ffff00' rel='gb_page_fs[]' title='Parodyk kitiems 8 seriją' href='/pasidalink-19577x10/'>
<img src="/templates/filmai_black/images/ico_tool_share.gif" />
</a>
</td>
<td>
<small>LT titrai</small>
</td>
<td>
<a rel='gb_page_center[528, 290]' title='Žiūrėti 8 seriją' href='http://www.filmai.in/watch.php?em=BuwgzpqtssiAGGcjeekz9PTI1NjQ0N2E~'>
<img src="/templates/filmai_black/images/play_icon.png" width="20" onclick='set_watched_cookie_serial("19577x10", "done-tick-full-series")' />
</a>
</td>
I am using the pattern:
<td><small>(.*)</small></td>
<td><a rel='gb_page_center[528, 290]' title='Žiūrėti (.*) seriją' href='(.*)'><img src=
I want to get the content in the (.*) location into an array.
Can someone please correct my pattern and explain it?
I want to learn to use regular expressions.
"Don't use Regex to parse HTML" aside,
here are a few uber simple steps to learning Regexp.
Download and install RegexBuddy
Run RegexBuddy
Start with something easy and then FLY! :)
the expression you are looking for is:
<small>(.*)</small>
It finds all characters found inbetween small tags and puts them into backreferences.
Think of Backreference as an Array. The first to item found, is 0, next is 1 and so on.
// command:
preg_match_all('%<small>(.*)</small>%i', $subject, $result, PREG_PATTERN_ORDER);
// $result[0]
Array
(
[0] => <small>LT titrai</small>
)

Categories