PHP gallery integrating CSS - php

i have this code made in PHP , i integrated a css code by <<<HTML using variable $style the style shows up 3 times in the back of images for the gallerys, i suspect 3 times it shows up because of the number of the images, my wish was to show up only once.
i don't get it what it shows up by the number of images ? !
<?php
if( ! defined( 'CMSFUTURE' ) ) {
die( "Hacking attempt!" );
}
$style = <<<HTML
<style>
.gallerypro{padding:5px 5px 0 5px;height: 120px; width: 543px; background-color: rgb(220,220,220); border:1px solid grey; box-shadow: 7px 8px 20px -5px rgba(0,0,0,0.47);}
</style>
HTML;
$distr_charset = "utf-8";
$self_id ='';
$homeUrl = $config['http_home_url'];
$rootPath = $_SERVER['DOCUMENT_ROOT'];
$fullpath = $rootPath."/uploads/jmgallery/";
include ('engine/api/api.class.php');
if($dle_module == "showfull") {
$id = $_GET['newsid'];
$getCg = $dle_api->load_table($table="dle_jmgallery", $fields="id", $where="id > 0", $multirow="false", $start="0", $limit="0", $sort="", $sort_order="");
$having = FALSE;
foreach($getCg as $g){
if($g['id'] == $id){$having = TRUE;}
}
if($having == TRUE){
$getGal = $dle_api->load_table($table="dle_jmgallery", $fields="*", $where="id > 0", $multirow="true", $start="0", $limit="0", $sort="", $sort_order="");
foreach($getGal as $carousel){
$sizeW = $carousel['sizew'];
$sizeH = $carousel['sizeh'];
$dist = $carousel['distance'];
$self_id = $carousel['id'];
if($self_id == $id){
$mask = "*.jpg";
$idN = $fullpath.$id."/";
$mask = $idN.$mask;
if($sizeH == "0"){$sizeH = $sizeW; }
foreach (glob($mask) as $filename) {
$fileRname = substr($filename, -14);
$picSizeW = $sizeW * 2;
$img = "<img src='/uploads/jmgallery/$id/$fileRname' width='".$picSizeW."px' />";
$galery .= "$style<div class='gallerypro'><a style='overflow:hidden; display:block; float:left; margin:".$dist."px 0 0 ".$dist."px; width:".$sizeW."px; height:".$sizeH."px;' href='".$homeUrl."uploads/jmgallery/$id/$fileRname' onclick='return hs.expand(this)'>$img</a>"; } $xJ ="Computer repair"; $xJ = iconv("UTF-8", "UTF-8", $xJ); $galery .="<a href='$sitename' style='display:none; '>$xJ</a></div>";
echo $galery."<br clear='left' />";
}
}
}
$having = FALSE;
}
?>
This is the result i get :
See in the background of images ? that style is from variable $style declared above , and used in :
$galery .= "$style<div class='gallerypro'><a style='overflow:hidden; display:block; float:left; margin:".$dist."px 0 0 ".$dist."px; width:".$sizeW."px; height:".$sizeH."px;' href='".$homeUrl."uploads/jmgallery/$id/$fileRname' onclick='return hs.expand(this)'>$img</a>"; } $xJ ="Computer repair"; $xJ = iconv("UTF-8", "UTF-8", $xJ); $galery .="<a href='$sitename' style='display:none; '>$xJ</a></div>";

Move $style out of foreach statement.
If you place it inside foreach, it will displayed as many as foreach loop.
I don't know why you used to many foreach.
Just another suggestion, make up your code for better debugging. You also need to know about how to place a container/wrapper for your element.
See update of your code.
<?php
if( ! defined( 'CMSFUTURE' ) ) {
die( "Hacking attempt!" );
}
$style = <<<HTML
<style>
.gallerypro{padding:5px 5px 0 5px;height: 120px; width: 543px; background-color: rgb(220,220,220); border:1px solid grey; box-shadow: 7px 8px 20px -5px rgba(0,0,0,0.47);}
</style>
HTML;
$distr_charset = "utf-8";
$self_id ='';
$homeUrl = $config['http_home_url'];
$rootPath = $_SERVER['DOCUMENT_ROOT'];
$fullpath = $rootPath."/uploads/jmgallery/";
include ('engine/api/api.class.php');
if($dle_module == "showfull") {
$id = $_GET['newsid'];
$getCg = $dle_api->load_table($table="dle_jmgallery", $fields="id", $where="id > 0", $multirow="false", $start="0", $limit="0", $sort="", $sort_order="");
$having = FALSE;
foreach($getCg as $g){
if($g['id'] == $id){$having = TRUE;}
}
if($having == TRUE){
$getGal = $dle_api->load_table($table="dle_jmgallery", $fields="*", $where="id > 0", $multirow="true", $start="0", $limit="0", $sort="", $sort_order="");
$galerry = $style."<div class='gallerypro'>";
foreach($getGal as $carousel){
$sizeW = $carousel['sizew'];
$sizeH = $carousel['sizeh'];
$dist = $carousel['distance'];
$self_id = $carousel['id'];
if($self_id == $id){
$mask = "*.jpg";
$idN = $fullpath.$id."/";
$mask = $idN.$mask;
if($sizeH == "0"){$sizeH = $sizeW; }
foreach (glob($mask) as $filename) {
$fileRname = substr($filename, -14);
$picSizeW = $sizeW * 2;
$img = "<img src='/uploads/jmgallery/$id/$fileRname' width='".$picSizeW."px' />";
$galery .= "<a style='overflow:hidden; display:block; float:left; margin:".$dist."px 0 0 ".$dist."px; width:".$sizeW."px; height:".$sizeH."px;' href='".$homeUrl."uploads/jmgallery/$id/$fileRname' onclick='return hs.expand(this)'>$img</a>";
}
$xJ ="Computer repair";
$xJ = iconv("UTF-8", "UTF-8", $xJ);
$galery .="<a href='$sitename' style='display:none; '>$xJ</a>";
}
}
$gallery .= "</div>";
echo $gallery;
}
$having = FALSE;
}
?>

Related

Testing database speed with PHP

i am trying to test database speed with php script.
database connect time
database query time/execution time
database basic information like version, port etc
I am using : https://stackoverflow.com/a/39559173
I am trying :
<?php
/**
* Created by PhpStorm.
* User: NEO
* Date: 9/18/2016
* Time: 10:57 AM
*/
/**
* PHP Script to benchmark PHP and MySQL-Server
*
* inspired by / thanks to:
* - www.php-benchmark-script.com (Alessandro Torrisi)
* - www.webdesign-informatik.de
*
* #author odan
* #license MIT
*/
// -----------------------------------------------------------------------------
// Setup
// -----------------------------------------------------------------------------
set_time_limit(120); // 2 minutes
$options = array();
// Optional: mysql performance test
$options['db.host'] = '127.0.0.1';
$options['db.user'] = 'root';
$options['db.pw'] = '';
$options['db.name'] = 'bache3';
// -----------------------------------------------------------------------------
// Main
// -----------------------------------------------------------------------------
// check performance
$benchmarkResult = test_benchmark($options);
// html output
echo "<!DOCTYPE html>\n<html><head>\n";
echo "<style>
table {
color: #333; /* Lighten up font color */
font-family: Helvetica, Arial, sans-serif; /* Nicer font */
width: 640px;
border-collapse:
collapse; border-spacing: 0;
}
td, th {
border: 1px solid #CCC; height: 30px;
} /* Make cells a bit taller */
th {
background: #F3F3F3; /* Light grey background */
font-weight: bold; /* Make sure they're bold */
}
td {
background: #FAFAFA; /* Lighter grey background */
}
</style>
</head>
<body>";
echo array_to_html($benchmarkResult);
echo "\n</body></html>";
exit;
// -----------------------------------------------------------------------------
// Benchmark functions
// -----------------------------------------------------------------------------
function test_benchmark($settings)
{
$timeStart = microtime(true);
$result = array();
$result['version'] = '1.1';
$result['sysinfo']['time'] = date("Y-m-d H:i:s");
$result['sysinfo']['php_version'] = PHP_VERSION;
$result['sysinfo']['platform'] = PHP_OS;
$result['sysinfo']['server_name'] = $_SERVER['SERVER_NAME'];
$result['sysinfo']['server_addr'] = $_SERVER['SERVER_ADDR'];
test_math($result);
test_string($result);
test_loops($result);
test_ifelse($result);
if (isset($settings['db.host'])) {
test_mysql($result, $settings);
}
$result['total'] = timer_diff($timeStart);
return $result;
}
function test_math(&$result, $count = 99999)
{
$timeStart = microtime(true);
$mathFunctions = array("abs", "acos", "asin", "atan", "bindec", "floor", "exp", "sin", "tan", "pi", "is_finite", "is_nan", "sqrt");
for ($i = 0; $i < $count; $i++) {
foreach ($mathFunctions as $function) {
call_user_func_array($function, array($i));
}
}
$result['benchmark']['math'] = timer_diff($timeStart);
}
function test_string(&$result, $count = 99999)
{
$timeStart = microtime(true);
$stringFunctions = array("addslashes", "chunk_split", "metaphone", "strip_tags", "md5", "sha1", "strtoupper", "strtolower", "strrev", "strlen", "soundex", "ord");
$string = 'the quick brown fox jumps over the lazy dog';
for ($i = 0; $i < $count; $i++) {
foreach ($stringFunctions as $function) {
call_user_func_array($function, array($string));
}
}
$result['benchmark']['string'] = timer_diff($timeStart);
}
function test_loops(&$result, $count = 999999)
{
$timeStart = microtime(true);
for ($i = 0; $i < $count; ++$i) {
}
$i = 0;
while ($i < $count) {
++$i;
}
$result['benchmark']['loops'] = timer_diff($timeStart);
}
function test_ifelse(&$result, $count = 999999)
{
$timeStart = microtime(true);
for ($i = 0; $i < $count; $i++) {
if ($i == -1) {
} elseif ($i == -2) {
} else if ($i == -3) {
}
}
$result['benchmark']['ifelse'] = timer_diff($timeStart);
}
function test_mysql(&$result, $settings)
{
$timeStart = microtime(true);
$link = mysqli_connect($settings['db.host'], $settings['db.user'], $settings['db.pw']);
$result['benchmark']['mysql']['connect'] = timer_diff($timeStart);
//$arr_return['sysinfo']['mysql_version'] = '';
mysqli_select_db($link, $settings['db.name']);
$result['benchmark']['mysql']['select_db'] = timer_diff($timeStart);
$dbResult = mysqli_query($link, 'SELECT VERSION() as version;');
$arr_row = mysqli_fetch_array($dbResult);
$result['sysinfo']['mysql_version'] = $arr_row['version'];
$result['benchmark']['mysql']['query_version'] = timer_diff($timeStart);
$query = "SELECT BENCHMARK(1000000,ENCODE('hello',RAND()));";
$dbResult = mysqli_query($link, $query);
$result['benchmark']['mysql']['query_benchmark'] = timer_diff($timeStart);
mysqli_close($link);
$result['benchmark']['mysql']['total'] = timer_diff($timeStart);
return $result;
}
function timer_diff($timeStart)
{
return number_format(microtime(true) - $timeStart, 3);
}
function array_to_html($array)
{
$result = '';
if (is_array($array)) {
$result .= '<table>';
foreach ($array as $k => $v) {
$result .= "\n<tr><td>";
$result .= '<strong>' . htmlentities($k) . "</strong></td><td>";
$result .= array_to_html($v);
$result .= "</td></tr>";
}
$result .= "\n</table>";
} else {
$result = htmlentities($array);
}
return $result;
}
The above script is working fine but it does not have a option to add custom port for testing and it do not show information like execution time etc

Filtering string arrays in PHP

This uses Wolfram Alpha API to get planes nearby, then display it. How can I remove the plane direction and the phrase 'Slant distance'?
My code (PHP):
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value)
{
echo $key;
foreach($value as $value1){
echo $value1;
echo " ";
}
}
Sample output below:
slant distance ENY flight 3278
14 miles NNW Frontier Airlines flight 72
44 miles N American Airlines flight 1241
15 miles NW American Airlines flight 396
23 miles W Atlantic Southeast Airlines flight 6104
49 miles SSE
What I want it to look like:
Frontier flight 3278
Airlines flight 72
American Airlines flight 1241
American Airlines flight 396
Atlantic Southeast Airlines flight 6104
How's this?
foreach($value as $value1){
if(preg_match('~(flight\s+\d+)~mis', $value1, $flightdata) || preg_match('~\s+(.*?\s+Airlines)\s+~mis', $value1, $airlinedata)) {
if(!empty($flightdata[1])) {
echo $flightdata[1];
}
if(!empty($airlinedata[1])) {
echo $airlinedata[1];
}
echo $value1 . ' ' . "\n";
}
You didn't mention the hr's in your desired output but those should be easy enough for you to remove.
Updated (untested because I deleted the file after answering):
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '') {
$cols = $fields;
} elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value) {
foreach($value as $value1){
if(preg_match('~(flight\s+\d+)~mis', $value1, $flightdata) || preg_match('~\s+(.*?\s+Airlines)\s+~mis', $value1, $airlinedata)) {
if(!empty($flightdata[1])) {
echo $flightdata[1];
}
if(!empty($airlinedata[1])) {
echo $airlinedata[1];
}
echo $value1 . ' ' . "\n";
}
}
}
?>
olivr3000,
Somehow I did manage to screw up my edit above and didn't include the code that finally worked for my testing.
Here is the code with my edits
You can see it in action at
http://hdreports.com/test/testjson.php
and the source is
http://hdreports.com/test/testjson.txt
Here it is and it works. Sorry for the delay in getting it posted here correctly.
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
if ($flight === '') {
$cols = $fields;
} elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value) {
echo $key.'<BR>';
}
?>
Olivr3000 here is an update. I tried to edit Chris85 code to post this yesterday but my edit did not get published. I changed the final foreach to output the airline data as you requested
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '') {
$cols = $fields;
} elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value) {
foreach($value as $value1){
if(preg_match('~(flight\s+\d+)~mis', $value1, $flightdata) || preg_match('~\s+(.*?\s+Airlines)\s+~mis', $value1, $airlinedata)) {
if(!empty($flightdata[1])) {
echo $flightdata[1];
}
if(!empty($airlinedata[1])) {
echo $airlinedata[1];
}
echo $value1 . ' ' . "\n";
}
}
}
?>
which gives this HTML result
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style>
body {
background-color: rgba(255, 255, 255, 0.3);
font-family: 'Open Sans', sans-serif;
text-align:center;
}
</style>
</head>
American Airlines flight 1046<BR>N929FD<BR>
ENY flight 3238<BR>
Southwest Airlines flight 2477<BR>
American Airlines flight 2352<BR>
Your data structure changed at some point between the last answer and this. If this continues to happen these will never work.
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result') {
$parser->next('pod'); // jump to the next pod node
}
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
foreach ($lines as $line) {
if(preg_match('~^(.*?)\s+(flight\s+\d+)~', $line, $matches)){
echo $matches[1] . ' ' . $matches[2] . "\n";
}
}
?>
Output via my shell....
United Airlines flight 1274
Delta Air Lines flight 2389
Mesa Airlines flight 3734
United Airlines flight 569
Shuttle America flight 3473
United Airlines flight 1274
Delta Air Lines flight 2389
Mesa Airlines flight 3734
United Airlines flight 569
Shuttle America flight 3473

HTML on image not printing in pdf

This is my code
<?php
class Diagram
{
function outLet()
{
$boothsizer = 3;
if($boothsizer == 3){
$cellWidth = '112px';
$cellHeight = '52px';
$innerDivElectricTop = '41px';
$innerDivElectricLeft = '110px';
$backgroundImage = 'url(booth_top_images/5X20TOP.jpg)';
$width = '900px';
$height = '225px';
$sidewalls = 2;
$backwalls = 6;
}
else
if($boothsizer == 19)
{
$cellWidth = '144px';
$cellHeight = '145px';
$innerDivElectricTop = '105px';
$innerDivElectricLeft = '73px';
$backgroundImage = 'url(booth_top_images/10X10TOP.jpg)';
$width = '599px';
$height = '605px';
$sidewalls = 3;
$backwalls = 3;
}
$innerDivElectricWidth = $backwalls * $cellWidth;
$innerDivElectricHeight = $sidewalls * $cellHeight;
$output = '<div style="width:'.$width.'; height:'.$height.'; background-image:'.$backgroundImage.'">';
$output .= '<div id="inner_div_electric" style="position: relative; top: '.$innerDivElectricTop.'; left: '.$innerDivElectricLeft.';width:'.$innerDivElectricWidth.';height:'.$innerDivElectricHeight.'">';
for($i=1; $i<=$sidewalls; $i++)
{
for($j=1; $j<=$backwalls; $j++)
{
$output .= '<span class="droppable_class" style="width:'.($cellWidth-2).'; height:'.($cellHeight-2).'; border:1px solid red; float:left;display:inline-block;margin:0px;padding:0px;"></span>';
}
}
$output .= '</div></div>';
echo $output;
include("test/mpdf/mpdf.php");
$mpdf=new mPDF();
$mpdf->ignore_invalid_utf8 = true;
$stylesheet = file_get_contents('appstyle_pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($output);
$comname = "vam";
$name = "test/generated_pdfs/".str_replace(" ","-",$comname).".pdf";
$mpdf->Output($name,"F");
}
}
$diag = new Diagram;
print $diag->outLet();
?>
In my code I am trying to generate some squares upon images and trying to generate a pdf, when I echoed the $output I can see squares on images, but in my generated pdf only the image is printing, squares are not?
Anybody any ideas???
Change the <span> tags to <div> tags and it should work.
Unfortunately I don't have any explaination for the solution at the moment. According the mpdf script <span> tags are part of the enabledtags collection - mpdf.php Line 23249. So I'm not totally sure why <div> works and <span> doesn't.

Convert CSS font shorthand to long hand

Given a font CSS string such as this:
font:italic bold 12px/30px Georgia, serif;
or
font:12px verdana;
I want to convert it to its long hand format i.e:
font-style: italic; font-weight: bold;
Here is my miserable attempt: http://pastebin.com/e3KdMvGT
But of course it doesn't work for the second example since its expecting things to be in order, how can I improve it?
Here is a function which should do the work. The problem lies in the font-style, font-variant and font-weight properties and the value "normal" as you can read in the css specs ([[ <'font-style'> || <'font-variant'> || <'font-weight'> ]? <'font-size'> [ / <'line-height'> ]? <'font-family'> ] | caption | icon | menu | message-box | small-caption | status-bar | inherit).
$testStrings = array('12px/14px sans-serif',
'80% sans-serif',
'x-large/110% "New Century Schoolbook", serif',
'x-large/110% "New Century Schoolbook"',
'bold italic large Palatino, serif ',
'normal small-caps 120%/120% fantasy',
'italic bold 12px/30px Georgia, serif',
'12px verdana');
foreach($testStrings as $font){
echo "Test ($font)\n<pre>
";
$details = extractFull($font);
print_r($details);
echo "
</pre>";
}
function extractFull($fontString){
// Split $fontString. The only area where quotes should be found is around font-families. Which are at the end.
$parts = preg_split('`("|\')`', $fontString, 2, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$chunks = preg_split('` `', $parts[0], NULL, PREG_SPLIT_NO_EMPTY);
if(isset($parts[1])){
$chunks[] = $parts[1] . $parts[2];
}
$details = array();
$next = -1;
// Manage font-style / font-variant / font-weight properties
$possibilities = array();
$fontStyle = array('italic', 'oblique');
$fontVariant = array('small-caps');
$fontWeight = array('bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900');
// First pass on chunks 0 to 2 to see what each can be
for($i = 0; $i < 3; $i++){
$possibilities[$i] = array();
if(!isset($chunks[$i])){
if($next == -1){
$next = $i;
}
continue;
}
if(in_array($chunks[$i], $fontStyle)){
$possibilities[$i] = 'font-style';
}
else if(in_array($chunks[$i], $fontVariant)){
$possibilities[$i] = 'font-variant';
}
else if(in_array($chunks[$i], $fontWeight)){
$possibilities[$i] = 'font-weight';
}
else if($chunks[$i] == 'normal'){
$possibilities['normal'] = 1;
}
else if($next == -1){
// Used to know where other properties will start at
$next = $i;
}
}
// Second pass to determine what real properties are defined
for($i = 0; $i < 3; $i++){
if(!empty($possibilities[$i])){
$details[$possibilities[$i]] = $chunks[$i];
}
}
// Third pass to set the properties which have to be set as "normal"
if(!empty($possibilities['normal'])){
$properties = array('font-style', 'font-variant', 'font-weight');
foreach($properties as $property){
if(!isset($details[$property])){
$details[$property] = 'normal';
}
}
}
if(!isset($chunks[$next])){
return $details;
}
// Extract font-size and line height
if(strpos($chunks[$next], '/')){
$size = explode('/', $chunks[$next]);
$details['font-size'] = $size[0];
$details['line-height'] = $size[1];
$details['font-family'] = $chunks[$next+1];
}
else if(preg_match('`^-?[0-9]+`', $chunks[$next]) ||
in_array($chunks[$next], array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'))){
$details['font-size'] = $chunks[$next];
$details['font-family'] = $chunks[$next+1];
}
else{
$details['font-family'] = $chunks[$next];
}
return $details;
}
here my attempt
function rewriteFont($short) {
$short = str_replace("font:","",$short);
$values = explode(" ", $short);
$length = count($values);
$familyLength = 0;
for($i = 0; $i < $length; $i++) {
$currentValue = $values[$i];
if($currentValue == 'italic' || $currentValue == 'oblique' ) {
echo "font-style:{$currentValue};";
}
else if($currentValue == 'small-caps') {
echo "font-variant:{$currentValue};";
}
else if ($currentValue == 'bold' || $currentValue == 'bolder' || $currentValue == 'lighter' || is_numeric($currentValue) ) {
echo "font-weight:{$currentValue};";
}
else if (strpos($currentValue, "px") || strpos($currentValue, "em") || strpos($currentValue, "ex")|| strpos($currentValue, "pt")
|| strpos($currentValue, "%") || $currentValue == "xx-small" || $currentValue == "x-small" || $currentValue == "small"
|| $currentValue == "medium" || $currentValue == "large" || $currentValue == "x-large" || $currentValue == "xx-large") {
$sizeLineHeight = explode("/", $currentValue);
echo "font-size:{$sizeLineHeight[0]};";
if(isset($sizeLineHeight[1])) {
echo "line-height:{$sizeLineHeight[1]};";
}
}
else {
if($familyLength == 0) {
echo "font-family:{$currentValue} ";
}
else {
echo $currentValue;
}
$familyLength++;
}
}
}
Following the specs, I'd do the following code. It works with all examples from the specs. You can see it here : http://codepad.viper-7.com/ABhc22
function font($s){
$fontStyle = array('normal', 'italic', 'oblique', 'inherit');
$fontVariant = array('normal', 'small-caps','inherit');
$fontSize = array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large');
$fontWeight = array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'inherit');
$s = str_replace('font: ', '', $s);
$array = explode(' ', $s);
$count = count($array);
$sizeFound = false;
$final = array();
$final['font-style'] = 'normal';
$final['font-variant'] = 'normal';
$final['font-weight'] = 'normal';
for($i = 0; $i < $count; $i++){
$cur = $array[$i];
if($sizeFound){
$final['font-family'] = isset($final['font-family']) ? $final['font-family'].$cur : $cur;
}else if(strripos($cur,'%') !== false || strripos($cur,'px') !== false || in_array($cur, $fontSize)){
$sizeFound = true;
$size = explode('/', $cur);
if(count($size) > 1){
$final['font-size'] = $size[0];
$final['line-height'] = $size[1];
}else
$final['font-size'] = $size[0];
}else{
if(in_array($cur, $fontStyle))
$final['font-style'] = $cur;
if(in_array($cur, $fontVariant))
$final['font-variant'] = $cur;
if(in_array($cur, $fontWeight))
$final['font-weight'] = $cur;
}
}
$ret = '';
foreach($final as $prop => $val)
$ret .= $prop.': '.$val.';';
return $ret;
}
I guess it can be optimised. :)
You could look at CSSTidy, whose code is open-source and try to reverse engineer it.

Problems with preg_replace and ? (question mark) - what to do?

I have made this line of code to make the words, that is searced for, enhanced.
$tekst = preg_replace("/($searchstr)/i", '<span style="color: 8fb842; font-weight: bold;">$1</span>', $tekst);
But my problem is, that when I make $searchstr = '?'; it is setting between every letter in the $tekst string.
The whole script is:
/////////////////////////////////
// Set variables and arrays
/////////////////////////////////
$arr_sim = array();
if( !empty($_GET['search']) )
{
$text=strtolower($_GET['search']);
$code_entities_replace = array(' ','--','"','!','#','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','~','`','=', 'Æ', 'æ', 'æ', 'ø', 'Ø', 'ø', 'å', 'å', 'Å');
$code_entities_match = array('-','--','','_quot_','_s_','_s-a_','_sq_','procent','_tria_','_and_','_star_','_par-st_','_par-end_','_us_','_plus_','_tub-st_','_tub-end_','_line_','_col_','_anf_','_lt_','_st_','_qm_','_sqpar-s_','_sqpar-e_','_backsla2_', '_semcol_','_1anf_','_comma_','_punc_','_slash_','_nearequ_', '_msql-anf_', '_equal_', 'ae', 'ae', 'ae', 'oe', 'oe', 'oe', 'aa', 'aa', 'aa');
$text = str_replace($code_entities_match, $code_entities_replace, $text);
$searchstr = $text;
$search_str = $showpages->escape_str($text);
$showpages->_table = 'pages';
$showpages->_where = " tekst LIKE '%". $search_str . "%' AND language_id = '" . $_SESSION['lang_id']. "'";
$showpages->_orderby = 'id';
$showpages->_order = 'desc';
$f = $showpages->search();
while ( $row = mysql_fetch_array($f) )
{
$arr_text = explode(" ",$row['tekst']);
$percent = 0;
$words = count($arr_text);
foreach( $arr_text as $k => $v )
{
similar_text($search_str, $v, $p);
$percent += $p;
}
$percent = $percent / $words;
$arr_sim[] = array('percent' => $percent, 'id' => $row['id']);
}
}
/////////////////////////////////
// Set some variables
/////////////////////////////////
$arr_len = count($arr_sim);
if( !empty($_GET['offset']) )
$offset = $showpages->escape_str($_GET['offset']);
else
$offset = 0;
if( $arr_len >= 15 )
{
$limit = 15;
} else {
$limit = $arr_len;
}
$start = $offset+$limit;
rsort($arr_sim); // Sort the array to make the script show in the right order.
/////////////////////////////////
///////////////////
// Show content
////////////////////
if( $arr_len > 0 )
// check if the search is performed and any hits were found.
{
for( $i = $offset; $i < $start; $i++)
{
// $arr_sim[$i]['id']
$showpages->_table = 'pages';
$showpages->_id = $arr_sim[$i]['id'];
$showpages->_orderby = 'id';
$showpages->_order = 'desc';
$z = $showpages->search();
$r = $showpages->fetch_array( $z );
$tekst = strip_tags($r['tekst'], "<p><a>");
$str_pos = strpos($tekst, $searchstr);
if( $str_pos > 50 ){
$start_str = '...';
if(strlen($tekst) > 200)
{
$end_str = '...';
}
$tekst = substr($tekst, $str_pos-50, 200);
} else {
$start_str = '';
if(strlen($tekst) > 200)
{
$end_str = '...';
}
$tekst = substr($tekst, 0, 200);
}
$tekst = preg_replace("/($searchstr)/i", '<span style="color: 8fb842; font-weight: bold;">$1</span>', $tekst);
$dataa .= '<style type="text/css">.search-fr { margin-bottom: 15px; } .search-fr a {padding: 0; margin: 0 0 5px 0; font-weight: bold; font-size: 14px;} .search-fr p { padding: 0; margin: 0;}</style>';
$dataa .= '<div class="search-fr">';
$dataa .= '' . $r['emne'] . ' - Matcher din søgning <b>'. round($arr_sim[$i]['percent']).'%</b><br />';
$dataa .= $start_str.$tekst.$end_str;
$dataa .= '</div>';
}
} else {
$dataa .= 'Der er ikke fundet nogle sider, der matcher din søgning. Prøv igen.';
}
You can run the preg_quote() function on $searchstr which will escape any metacharacters before the string is used as your pattern.
For example:
$tekst = preg_replace('/'.preg_quote($searchstr, '/').'/i', '<span style="color: 8fb842; font-weight: bold;">$1</span>', $tekst);

Categories