How do I highlight text in PHP with conditions? - php

I have some numbers, and depending on the number's value I need to highlight a string which is in a table. The table is not in database.
Does anyone know how to highlight text in php?

PHP won't "highlight" text, that is done with CSS/HTML. You only use PHP to output the correct HTML.
Something like this:
$my_num = 9;
foreach ($my_array_of_numbers as $num)
{
// See if $num matches $my_num, if so - add the "highlight"
// class to the HTML element we're using
$css_class = ($num == $my_num) ? 'highlight' : '';
echo '<td class="'.$css_class.'">'.$num.'</td>';
}
Then in your CSS:
.highlight {
background:yellow;
}
You may also want to consider using javascript for this, which can handle the task after the HTML has already been generated.

Presentation, like highlighting, is done in CSS, not PHP.
My advice would be to create a CSS class which has a background-color defined to be used as highlighting. Then, in PHP, you can conditionally wrap your string in <span> tags which have that class, so the text would be highlighted.
CSS:
.highlight {
background-color: #FF0;
}
PHP:
if (highlightCondition) {
echo '<span class="highlight">' . $string . '</span>';
} else {
echo $string;
}

Related

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.

Select multiple divs and change their backgrounds

I am creating multiple divs in a loop in php shown below.
<?php
for ($i=0; $i<=9; $i++)
{
for ($j=0; $j<=9; $j++)
{
echo "<div class=\"bg\" id=\"aaa".$i."\" style=\" position:absolute;top:".($i*10)."%;left:".($j*10)."%;\">
</div>";
}
}
?>
i want to select multiple divs (not all) and change their backgrounds using jquery. i cant seem to be able to figure out how to proceed with this
You can select div with id starting with aaa
$('div[id^=aaa]')
if you want to select yhe div's based on their index, you could use the nth-of-type selector:
divs = $('.bg:nth-of-type(1)');
divs.css('background-color','blue');
You can select multiple elements by adding them to the variable:
divs.add('.bg:nth-of-type(2)').add('.bg:nth-of-type(3)');
Note that these are css selectors so it may be an idea to simply do this in css:
.bg:nth-of-type(1),
.bg:nth-of-type(2),
.bg:nth-of-type(3){
background-color: blue;
}
also note you can use an expression inside the brackets to represent multiple values in a sequence.
.bg:nth-of-type(3n+1){ //will select every fourth div
background-color: blue;
}
Unless you can come up with a better criteria for which div's you want to change, this is probably the best way.
Source(s)
jQuery API - .add()
MDN - CSS :nth-of-type selector
This should do the trick:
var arrayDivs = $('div[id^=aaa]');
$.each(arrayDivs, function(){
$(this).css('background-color', '#000');
});
If you want to select multiple lists and not all "aaa"+integer ones, you will need to either know the numbers of those or you need to differ within your loops already.
More information would be awesome!
The "proper" way (if you can say that) would be to group the elements you want to assign common properties with appropriate classes. You can then manipulate them via CSS
So in essense, while looping in the above code :
for ($i=0; $i<=9; $i++) {
for ($j=0; $j<=9; $j++) {
$classes = 'bg';
if( [somelogic] ) { $classes .= ' bluefront'; }
if( [otherlogic] ) { $classes .= ' greenback'; }
echo "<div class=\"".$classes."\" id=\"aaa".$i."\" style=\" position:absolute;top:".($i*10)."%;left:".($j*10)."%;\"></div>";
}
}
and then, via CSS :
.bg.bluefront { color: blue; }
.bg.greenback.bluefront { background-color: green; color: white; }
//select all elements with class bg and add background image
$('.bg').css('background-image',"url('some_image.gif')");
better yet use css:
.bg {
background-image: url('some_image.gif');
}
if you only want some divs from the class bg:
$('.bg').each(function(index,element){
//your code here eg:
if(index == 2)
alert(index);
});

Using php variables and css to change the background color based on events and sql data

Hope this makes sense, I'll hopefully paint a clear picture.
<?php $rx_event_color = $rx_image_color = '#FF0000';
if ($a['rx_event_exists'] == 1) { $rx_event_color = '#00FF00'; }
if ($a['rx_scanned'] == 1) { $rx_image_color = '#00FF00'; }
else if ($a['rx_scanned'] > 1) { $rx_image_color = '#FFFF00'; }
?>
I don't want the whole background td to change color, only the text inside the td based on the event (data in sql)
if ($a['rx_event_exists'] == 0)
{
echo "<tr><td style='background:$rx_event_color'><a href='"
. matry::here_to('new', array('tfilt'=>'WR', 'pfilt'=>$patient->code))
. "'>**Rx Event Not Created**</a></td></tr>";
}
I tried to just change background to color and also tried adding it in a div instead... i figured it should be easier than it's turning out to be.. that's why i'm asking here. Thanks in advance my friends.
You need to move the style attribute to the anchor tag, as the link's styling is controlling the coloring of the text, not the td. Color and background-color can be used interchangeably here, depending on your purposes.
<td><a href='...' style='color:$rx_event_color'>...</a></td>
Alternately, you could use classes:
.notfound a { color: red }
<td class="notfound">...</td>

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

Highlighting Text: How to echo HTML DOM element with all tags

I want to highlight specified keywords in the body of an HTML document. At first I used preg_replace to put a < span > around the keywords, but of course that caused problems if the keyword was part of a tag, like the letter "i" (as in < li >). So instead, I'm using DOM::loadHTMLFile(path) to load the document, and then use the preg_replace inside the values of each child.
So far, so good. I can echo out the plain text of the document with the appropriate words highlighted and no interference from tags. But I need to echo the entire body of the text including the tags after the changes, and I don't know how. Here's what I have so far:
if (file_exists('mss/'.$link_title)) {
$descfile = DOMDocument::loadHTMLFile('mss/'.$link_title);
foreach ($descfile->childNodes as $e) {
$desc_output = $e->nodeValue;
$desc_output = preg_replace($to_highlight, "<span class=\"highlight\">$0</span>", $desc_output);
}
echo ???
}
What should I echo?
If you change your code to:
$e->nodeValue = preg_replace($to_highlight, "<span class=\"highlight\">$0</span>", $e->nodeValue);
You can probably use:
http://php.net/manual/de/domdocument.savehtml.php
to output your entire html document.

Categories