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
. Thenecho
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
Now you have all your data in a array. Each word is in it’s object.
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
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: