How can the last word of an element be styled? - css

Given a dynamically loaded heading (using PHP/WordPress) is there a pure CSS method of styling the final word? For instance:
<h1 class='featured'> This is my page title</h1>
Becomes
<h1 class='featured'> This is my page <span id="finalWord">title</span></h1>
If using CSS is not viable, is exploding the content of the <h1> tag the suggested way to do this?

AFAIK there is not a :last-word pseudo class in CSS (although that would be cool). You could use JavaScript for something like this, but if you have access to the <h1> server-side I'd do it with PHP. It's going to be part of the source code and probably easier.
A simple algorithm would be to find the last space in the string with strrpos() and use substr() to piece it back together wrapped in <span>.

I guess a really crude way would be to create a way to all the words and put it in a PHP array. Then echo all the values, and if it's the last one then put the <span id="finalWord"> before and the </span> after.
EX:
Step 1: Create the array
$your_text = "Your text goes here";
$pieces = explode(" ", $your_text);
Now you have all your data in a array. Each word is in it's object.
echo "<h1 class='featured'>";
$the_count = count($pieces);
foreach ($your_text as $i => $value) {
$i = $i + 1;
if ($i == $the_count) { echo "<span id='finalWord'>"; }
echo $value;
if ($i == $the_count) { echo "</span>"; }
}
echo "</h1>";
So basically what this code does is count how many objects are in your array and will check if the object being displayed is the last one. If it is, it will put the correct ID on it.
I just typed this code out real quick, so there could be some errors.
Coulton

is there a pure CSS method of styling
the final word
No such method in principle. CSS cannot modify the DOM.
Take text of dom element, find last word using your own criteria for the "word", wrap it into span and set innerHTML by the result.

Sorry for the follow up on an ancient post, this is the one that came up in my google searches for "wrap the last word in a string with a span tag using php" so I figured this is where I would put the solution I came up with.
Using the above as a starting point, I created this function to accomplish what I needed:
function wrap_last($string, $wrap_start = '<span class="font-bold">', $wrap_finish = '</span>') {
$string_array = explode(' ', $string);
$count = count($string_array);
$new_array = array();
foreach ($string_array as $i => $value) {
$i = $i + 1;
$array_part = '';
if ($i == $count) {
$array_part .= $wrap_start;
}
$array_part .= $value;
if ($i == $count) {
$array_part .= $wrap_finish;
}
$new_array[] = $array_part;
}
$new_string = implode(' ', $new_array);
return $new_string;
}

Related

Show shortcode for a given word only once

I'm trying to implement a custom functionality to a wordpress shortcode plugin that shows a tooltip for specified words by automatically calling for information from Wikipedia.
Currently my code snippet works fine, but it shows the tooltips for each occurrence of the word in an article. For example if I specified the word : "dessert" in an array it will show the tooltip for all 5 words "dessert" found in the post. I'm looking for a way to limit the tooltip shortcode to be applied only once per word ( in this case "dessert" which has been specified in the array).
Me code snippet is this:
function add_wikitips($content) {
if( is_single() && is_main_query() ) {
$arr = array('dessert');
for ($i = 0; $i < count($arr); $i++) {
$content = str_replace($arr[$i], '[wiki]'.$arr[$i].'[/wiki]', $content);
}
}
return $content;
}
add_filter('the_content', 'add_wikitips');
I tried adding ob_end_clean(); then
static $content = null;
if ($content === null) {
return $content;
}
, but these methods didn't work. Probably because I didn't implement them properly.
Thanks a lot in advance for any advice and suggestions.
Probably, you can try this: Using str_replace so that it only acts on the first match?
You want the first work to have Wiki link. So replace the first occurrence only when you are doing str_replace()
May be like:
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');
// outputs '123def abcdef abcdef'
Mentioned in Karim's amswer

Symfony DomCrawler get HTML without attributes / styles

I need a way to get a HTML from an email without attributes (class / styles).
Currently trying the following:
$crawler = new Crawler();
$crawler->addHtmlContent($mail->textHtml);
$html = '';
$nodes = $crawler->filter('body > *'); //only stuff inside body
foreach ($crawler as $domElement) {
//remove somehow class+styles ?
$html .= $domElement->ownerDocument->saveHTML($domElement);
}
echo $html; //outputs everything inside body (currently with attributes)
As I read on many questions already, regex is not a good solutions for something like this as it may break stuff.

php find and remove from content img string

I have a little problem, how correct can i find img src string who ends with dealer.jpg and remove only this string from my content? for example:
<?php
$content = '<b>this is a content</b><img src=http://adress.com/as5.jpg><br> this is a content <img src=http://www.another-adress.com/dealer.jpg>';
$inf = explode("/dealer.jpg", $content);
$string = str_replace("<img src=\"$inf[0]/dealer.jpg\">", "", $content);
?>
I use this because I dont know image link, link always is another, but I know this link ends with dealer.jpg , and this script is not working... so can some one help me how correct do this ? normaly I whant to remove ads from page that i scraped. Thank you !
If i understood correctly you are trying to remove the img tag that ends with "dealer.jpg" (no matter the domain), right? try this:
$content = '<b>this is a content</b><img src=http://adress.com/as5.jpg><br> this is a content <img src=http://www.another-adress.com/dealer.jpg>';
$content = preg_replace('/<img src=[A-z0-9-_":\.\/]+\/dealer\.jpg>/', '', $content);
var_dump($content);
Edit
This second example will match the img tag even if it has another attributes such as alt, width, etc (but again, must end with "dealer.jpg")
$content = '<b>this is a content</b><img src="http://adress.com/as5.jpg"><br> this is a content <img alt="dealer-image" width="120" height="40" src="http://www.another-adress.com/dealer.jpg">';
$content = preg_replace('/<img[A-z0-9-_:="\.\/ ]+src="[A-z0-9-_:\.\/]+\/dealer\.jpg">/', '', $content);
var_dump($content);
Obs: I changed the initial $content because i've noticed it was missing the double quotation for src attribute. Not sure if was a typo or your string really looks like this.
Edit 2
Here is a example using DOM (a guess that is the best aproach here since the order of attributes could change):
$content = '<b>this is a content</b><img src="http://adress.com/as5.jpg"><br> this is a content <img alt="dealer-image" width="120" height="40" src="http://www.another-adress.com/dealer.jpg">';
// creates a DOMDocument based on your string, and wraps it in a div
$dom = new DOMDocument();
$dom->loadHTML("<div>{$content}</div>", LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
// get all img tags
$imgs = $dom->getElementsByTagName('img');
foreach ($imgs as $img) { // if they have that src, remove it from $dom
if (strpos($img->getAttribute('src'), 'dealer.jpg')) {
$img->parentNode->removeChild($img);
};
}
// get all the content of my first div, and print it
$newContent = $dom->getElementsByTagName('div')->item(0);
foreach ($newContent->childNodes as $childNode) {
var_dump($dom->saveHTML($childNode));
}

Tag list Drop Down Menu

I am wondering how to create a simple tag drop-down menu (all tags included DESC) without rewriting the WP core functions. It has to work outside of any loop.
wp_tag_cloud() with the 'format=array' attribute would seem the best choice since it works outside of any loop/template and returns all available tags sorted A-Z (which I need) but the array values contain HTML formatting (instead of just a plain string value) and that is not suitable for creating the drop-down.
i.e.:
<?php $tag = wp_tag_cloud('format=array'); // 'format=array' contains <a>link</> !!!
foreach($tag as $tagkey => $tagvalue) // ...need to be somehow filtered out !!
{
echo "<option value='".$tagvalue."'>".$tagvalue."</option>";
}
?>
The get_the_tag_list() function works great but it doesn't work outside of the template (loop).
Is there a simple way how to get the list of all tags so I can put them into the drop-down?
...OMG! I can't believe I actually asked this publicly!
Of course the code is ...
<?php $tag = wp_tag_cloud('format=array' );
foreach($tag as $tagkey => $tagvalue)
{
$cleanedup = strip_tags($tagvalue);
echo "<option value='".$cleanedup."'>".$cleanedup."</option>";
}
?>

Display different styles on alternate rows of table (within a loop)

I am populating a table with query results and I want the style of the rows to alternate i.e <tr> or <tr class="alt>. (Not using CSS3)
I using a while loop for displaying a row in my table for every result in the resultset.
How do I do this? I am lost.
Help please.
My solution:
if($i % 2) { //this means if there is a remainder
echo "<tr class='alt'>";
} else { //if there isn't a remainder we will do the else
echo "<tr>";
}
$i++;
With a regular for i loop, you'd use modulus (which is the % operator) on i to see if it's a multiple of 2.
In a while loop, you'll need to use another sort of incrementer, perhaps just declaring one before you loop and incrementing it each pass though:
$i = 0;
while (condition) {
$class = (i%2 == 0) ? 'alt' : '';
echo '<tr class="' + $class + '">';
$i++;
}
Caveat: I don't write much PHP, please treat the above as pseudo code. It should be pretty close to working though, if not straight-away correct.

Resources