White space render in html - Drupal 7? - php

When I used a module i have some problems. Some white space appeared
$content='';
$vocab = vuagame_getVocByName("the_loai_game");
$terms = taxonomy_get_tree($vocab->vid);
foreach ($terms as $term) {
$content.="<div class='contentBox'>";
$content.="<div class='contentBoxHeader'>";
$content.="<a href='/category/".$term->tid."'>".$term->name."</a>";
$content.="</div>";
$content.="<table class='gameTable' cellspacing='0' cellpadding='5'>";
$content.= views_embed_view('home', 'page', $term->tid);
$content.="</table>";
$content.="<div class='seemorelink'><a href='/category/".$term->tid."'>Xem thêm</a></div>";
$content.="</div><br/>";
}
return $content;
and here's the result with inspect element :
<div class="contentBox"><div class="contentBoxHeader">18+</div>
"
"
<table class="gameTable" cellspacing="0" cellpadding="5"><tbody><tr>
Does anyone can find out my trouble? Thanks a lot!

first, br tag is not a standard now.
debug it like this,
1)try the html without the loop first. or break the loop after its first cycle.
if white space still exits,
replace a href tag with
"&lta href='lorum.html'>ispum </a>"
and see if its gone.. there might be a chance of irregular tag open/close
if still it exists,
replace all data objects with just dummy text, if might have some faulty data.

What do you mean by "some white space appeared"? You get something displayed, but there is white space underneath it?
If that's the case, you could try with adding "clearfix" class to your output and adding this in your css file:
.clearfix:after {
content: "";
clear: both;
font-size: 0;
display: block;
height: 0;
visibility: hidden;
}
And yes, this seems unecessary, that could cause the problem too.

It's seems to be a encoding issue. Try to make sure you're saving your .tpl files with encode UTF-8
This should fix weird spaces.

Related

PHP HTML strip_tags all except some and remove styling from within tag

The HTML looks like this:
$html = 'SOME TEXT<p style="border-top: 0.0px;border-right: 0.0px;vertical-align: baseline;border-bottom: 0.0px;color: #000000;padding-bottom: 0.0px;padding-top: 0.0px;padding-left: 0.0px;margin: 0.0px;border-left: 0.0px;padding-right: 0.0px;background-color: #ffffff;">SOME TEXT';
I tried strip_tags($html, '<p>'); to remove everything except for <p> but that preserves all the style elements of the tag.
I want the above to be replaced with just <p>
What's the best approach?
Thanks!
The simplest solution for this would be something based on preg_replace().
$html = 'SOME TEXT<p style="border-top: 0.0px;border-right: 0.0px;vertical-align: baseline;border-bottom: 0.0px;color: #000000;padding-bottom: 0.0px;padding-top: 0.0px;padding-left: 0.0px;margin: 0.0px;border-left: 0.0px;padding-right: 0.0px;background-color: #ffffff;">SOME TEXT';
$html = strip_tags($html, '<p>');
$html = preg_replace('/\sstyle=["\'][A-Za-z0-9-:\s.;#]{1,}["\']/', '', $html);
As always, you should always be somewhat careful when trying to parse html with regex. For instance, this would fail if for some reason the text inside the <p /> tag contained something formatted like a css style. (Something like <p>If I typed style="color:red" inside the tags, it would also be removed</p>)
The next step to make something like this better would be to actually parse the string as an XML document using the DOMDocument class. It depends on how robust a feature set you are looking to achieve. However, this method could change your string in unexpected ways; for instance, parsing your string as a DOMDocument would cause a </p> tag to be added. That kind of validation may or may not be useful for you.
also some time very useful will remove style tag like below
`$html = '<style>li {
list-style: none;
background: url(/images/Articles/ordasoft_discount.png) no-repeat;
padding-left: 30px;
}
li p{font-size:16px}
ul li {
padding-left: 30px;}
.portfolio-container{width: 45%;}
</style> Hello word ';`
this will help:
`$html = preg_replace('/<style>[A-Za-z0-9-:\s.\/_;#\(\)\{\}%]{1,}<\/style>/', '',$html) ;`

Php echo hyperlink error with br

Issue 1:
In echo of php hyperlink working correctly,but linked to localhost(testing servor).Check:
echo '<a href> <div class="ws14"><span class="city"><br>' . $row['fura'] . '</br></span></div></a>';
When i got results displayed it is hyperlinked as i want and when click on it,it goes to localhost/trial.php (my testing script).Not going to hyperlinked url i have echoed.Please specify.For example if i echoed google.com then on clicking it must connect to that,but connecting to my localhost/trial.php.Thanks in advance.
Issue 2:
In br tag,we can specify difference between two line.I had done like:
.br {
line-height: 4; visibility:hidden;
}
And this is working correctly.But somehow, in same page we need 2 different br tags distance then how to do that?
For example in above it is simply line height of 4,now in other paragraph same page it require line height 8 with br tag,so how to do that? If i use br tags in both which br tag it will connect like of 8 or 4?
It may be bad question but very irritating.In short: how to use br tags in both with different dimensions(heights) in same page?
for issue 1:
echo '<span class="city"><br>' . $row['fura'] . '</br></span></div>';
for issue 2:
your br is class not a tag. so you have to apply css style to your div element. you can't give line-height to br tag. like as follows:
.brclass1
{
line-height: 4; visibility:hidden;
}
.brclass2
{
line-height: 8; visibility:hidden;
}
Apply particular div tag to class example as:
<div class="brclass1" >your content </div>
and other div element
<div class="brclass2" />your content </div>
You're href has no parameters
echo ' <div class="ws14"><span class="city">' . $row['fura'] .'<br/></span></div>'; //google.com is just an example
Br is not a class it is a tag. I don't know what you are trying to do with br tag. If you want to style your `$row['data']. Get your divs element.
For example:
.ws14 {
//your css here
}
.city{
//your css here
}

How do I change class name for CSS inside a PHP Loop?

Hello I am trying to change CSS content on some DIVs depending of their class name.
To explain better, I have a while loop in PHP reading from the database to output DIVs and I have a field named "section" with data such as A,B,C,D,E,F,G.
For the DIVs located in section "A" and "B" I want the class name to be desk_box_hor (for horizontal) ELSE I want it to desk_box_ver(vertical).
Below is what I tried doing only two sections (A,B) that need to be vertical. The others need to be horizontal. If theres a more efficient way of doing this please tell me. I have about 200 of these DIVs being output on screen.
If you have a better title please recommend one, I didn't know what to put lol.
Thanks in advance!
My fiddle of what I want both DIVs to look like
PHP:
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//draw a DIV box at its X,Y coordinate
//if section A and B do vertical
if($sec_name == 'B' || $sec_name == 'A'){
echo '<div class="desk_box_ver" data="'.$id.'" style="position:absolute;left:'.$x_pos.'px;top:'.$y_pos.'px;">id:'.$id.'</div>';
}
//else do it horizontal
else{
echo '<div class="desk_box_hor" data="'.$id.'" style="position:absolute;left:'.$x_pos.'px;top:'.$y_pos.'px;">id:'.$id.'</div>';
}
} //end while loop for desk_coord_result
CSS:
/* desk boxes*/
.desk_box_ver{
width: 23px;
height: 10px;
border: 4px solid black;
padding:10px;
}
.desk_box_hor{
width: 10px;
height: 23px;
border: 4px solid black;
padding:10px;
}
Also, lets say I want to use these two classes in the same Jquery function, is this the proper way of doing it?
$(".desk_box").add(".desk_box_ver").click(function() {
or
$(".desk_box, .desk_box_ver").click(function() {
In answer to your question "If theres a more efficient way of doing this please tell me." (I'll leave your other questions to someone else) yes, there are more efficient ways to write this PHP code, which then makes debugging and maintenance easier:-
a) Instead of two very long echo strings which are almost exactly the same, introduce a new PHP variable, say, $class. Then write:
$class = 'desk_box_hor';
if($sec_name == 'A' || $sec_name == 'B'){
$class = 'desk_box_ver';
}
echo '<div class="' . $class . '" data="' . $id . '" style="position:absolute;left:' . $x_pos . 'px;top:' . $y_pos.'px;">id:' . $id . '</div>';
Now you only have one long echo string to write, and to debug.
Also my preference is (though this is opinion only) to put a space either side of all those string concatenation dot operators - it makes it easier to decipher whats going on.
b) The next improvement you can make is to swap all the single and double quotes. Then you can write a single string with no concatenation operators at all, as you can put a PHP variable inside double quotes. Again, it makes the string of html clearer and easier to read, and debug. (Browsers can handle single or double quotes in the HTML tags). You end up with:
echo "<div class='$class' data='$id' style='position:absolute;left: $x_pos" . "px;top: $y_pos" . "px;'>id:$id</div>";
c) Next we can make the HTML code being created more readable; at the moment your script is generating a huge block of HTML markup (200 divs?) with no line breaks. Horrendous to debug. Just add \n to the end of your echo string like so:
echo ".....id:$id</div>\n";
and that will split the generated HTML markup into separate lines (but the onscreen text will be unaffected). Much easier then to see if one of the items went wrong (for instance, if the database returns an empty value for one of the records, it will stand out in the HTML like a sore thumb). Note that you can add \n inside a string surrounded by double quotes; if you stay with the original single quoted string you would have to add with a dot operator:
.....id:$id</div>' . "\n";
d) Lastly, you could cut out all those 200 position:absolute strings from the generated HTML markup by putting it into your CSS stylesheet, just retaining the CSS values that vary. Ie:
.desk_box_hor, .desk_box_ver { position: absolute; }
As regards why you are only getting vertical divs, never horizontal, I'll just try an educated guess. Are you really getting back from the database what you think you are?
For instance, you say in your comments the field name is "section", but the PHP is looking for a "section_name" field. Or is the data itself wrong? Have you got PHP error checking on, eg error(reporting(E_ALL)? If not, it would not return an error message, but still blindly go on reading through all rows in the db.
In that case it will always take the else part of your if...else. Supposedly this is the horizontal div path, but because the CSS has the width and height values the wrong way round (see above) it will actually produce vertical boxes all the time.

How do I extract a specific substring from a given HTML tag, without knowing for certain its length?

I want to do something like:
<?php
$text = "<font style='color: #fff'>";
$replaceandshow = str_replace("<font style=\"?\">", "the font style is ?", $text);
echo $replaceandshow;
?>
For example the ? is color: #fff, but I want that PHP will trace it by itself, Is it possible + If it's possible , How can I do that?
P.S: Someone gave me a code but it's now working, it displays a White page for me.
<?php
$colorstring = "<font style='#fff'>";
$searchcolor = preg_replace('[a-fA-F0-9]{3,6}','[font style=$1]Test[/font]',$colorstring);
echo $searchcolor;
Thanks for helping.
You are getting white page because error reporting is turned off. The error in your code is missing delimiter in preg_replace. And additionally, to use back-referencing you should enclose the expression required to match in parentheses.
preg_replace('/([a-fA-F0-9]{3,6})/','the font style is $1',$colorstring);
shall give the correct output.
You might consider using a more constrictive expression because the current expression is very open to matching other strings like "FFFont". Another thing to note is that the expression may result in output like.
<font style='color: the color is #fff'>
Try:
/<font style='color: #([a-fA-F0-9]{3,6})'>/
Since you need to pull basically any attribute out of any HTML you can use php XML parsing to do this.
<?php
$doc=new DOMDocument();
$doc->loadHTML("<html><body>Test<br><font style='color: #fff;'>hellow</font><a href='www.somesite.com' title='some title'>some site</a></body></html>");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$fonts=$xml->xpath('//font');
foreach ($fonts as $font) {
echo 'font style = '.$font['style']."<br />";
}
$as=$xml->xpath('//a');
foreach ($as as $a) {
echo 'href = '.$a['href'] . ' title = ' . $a['title']."<br />";
}
?>
That will return:
font style = color: #fff;
href = www.somesite.com title = some title
You can use a different foreach loop for each HTML tag you need to extract and then output any of the attributes you want.
Answer based on How to extract img src, title and alt from html using php?
This will work with simple style attributes:
$text = "<font style='color: #fff'>";
preg_match("/<font style=['\"]([^'\"]+)['\"]>/", $text, $matches);
echo "The font style is ".$matches[1];
For anything more complicated (ex: if it includes quotes), you'll need to use a HTML parser, such as http://www.php.net/manual/en/class.domdocument.php

extract css classes and ID's from source with php

I thought this was going to be pretty simple, but I've been struggling with it now for a while. I know there are CSS parser classes out there that can acheive what I want to do... but I don't need 95% of the functionality they have, so they're not really feasible and would just be too heavy.
All I need to be able to do is pull out any class and/or ID names used in a CSS file via regex. Here's the regex I thought would work, but hasn't.
[^a-z0-9][\w]*(?=\s)
When run against my sample:
.stuffclass {
color:#fff;
background:url('blah.jpg');
}
.newclass{
color:#fff;
background:url('blah.jpg');
}
.oldclass {
color:#fff;
background:url('blah.jpg');
}
#blah.newclass {
color:#fff;
background:url('blah.jpg');
}
.oldclass#blah{
color:#fff;
background:url('blah.jpg');
}
.oldclass #blah {
color:#fff;
background:url('blah.jpg');
}
.oldclass .newclass {
text-shadow:1px 1px 0 #fff;
color:#fff;
background:url('blah.jpg');
}
.oldclass:hover{
color:#fff;
background:url('blah.jpg');
}
.newclass:active {
text-shadow:1px 1px 0 #000;
}
It does match most of what I want, but it's also including the curly brackets and doesn't match the ID's. I need to match the ID's and Classes separately when conjoined. So basically #blah.newclass would be 2 separate matches: #blah AND .newclass.
Any ideas?
===================
FINAL SOLUTION
I wound up using 2 regex to first strip out everything between { and }, then simply matched the selectors based on the remaining input.
Here's a full working example:
//Grab contents of css file
$file = file_get_contents('css/style.css');
//Strip out everything between { and }
$pattern_one = '/(?<=\{)(.*?)(?=\})/s';
//Match any and all selectors (and pseudos)
$pattern_two = '/[\.|#][\w]([:\w]+?)+/';
//Run the first regex pattern on the input
$stripped = preg_replace($pattern_one, '', $file);
//Variable to hold results
$selectors = array();
//Run the second regex pattern on $stripped input
$matches = preg_match_all($pattern_two, $stripped, $selectors);
//Show the results
print_r(array_unique($selectors[0]));
[^a-z0-9][\w]+(?=\s)
I changed your * to a + match
It works fine in RegEXR - an awesome regex development tool: http://gskinner.com/RegExr/ (See bottom right of window to download the desktop version)
This version is based on nealio82's, but adding pseudo-selectors:
[^a-z0-9][\w:-]+(?=\s)
/(?<!:\s)[#.][\w]*/
some thing like this? excludes the #FFFFFF color stuff...
The solution posted by OP works, though it didn't work for me with CSS classes that had hyphens. As such, I've amended the second pattern to work more effectively:
$pattern_two = '/[\.|#]([A-Za-z0-9_\-])*(\s?)+/';

Categories