John Davidson

arrays - Add "first" and "last" classes to strings containing one or more <p> tags in PHP

0 comments
Message:


I have two strings I'm outputting to a page


# string 1
<p>paragraph1</p>

# string 2
<p>paragraph1</p>
<p>paragraph2</p>
<p>paragraph3</p>

What I'd like to do is turn them into this


# string 1
<p class="first last">paragraph1</p>

# string 2
<p class="first">paragraph1</p>
<p>paragraph2</p>
<p class="last">paragraph3</p>

I'm essentially trying to replicate the css equivalent of first-child and last-child, but I have to physically add them to the tags as I cannot use CSS. The strings are part of a MPDF document and nth-child is not supported on <p> tags.


I can iterate through the strings easy enough to split the <p> tags into an array


$dom = new DOMDocument();
$question_paragraphs = array();
$dom->loadHTML($q['quiz_question']);
foreach($dom->getElementsByTagName('p') as $node)
{
$question_paragraphs[] = $dom->saveHTML($node);
}

But once I have that array I'm struggling to find a nice clean way to append and prepend the first and last class to either end of the array. I end up with lots of ugly loops and array splicing that feels very messy.


I'm wondering if anyone has any slick ways to do this? Thank you :)


Edit Note: The two strings are outputting within a while(array) loop as they're stored in a database.



My Answer:
Here is a possible solution using PHP to add the "first" and "last" classes to the

tags in the array:

php
$dom = new DOMDocument();
$question_paragraphs = array();
$dom->loadHTML($q['quiz_question']);

// Get all

tags and store them in an array
foreach($dom->getElementsByTagName('p') as $node)
{
$question_paragraphs[] = $dom->saveHTML($node);
}

// Add "first" class to the first

tag
$question_paragraphs[0] = '

' . substr($question_paragraphs[0], 3);

// Add "last" class to the last

tag
$last_index = count($question_paragraphs) - 1;
$question_paragraphs[$last_index] = '

' . substr($question_paragraphs[$last_index], 3);

// Output the modified array
foreach($question_paragraphs as $paragraph)
{
echo $paragraph;
}


This code snippet first loads the HTML content into a DOMDocument and extracts all

tags into an array. Then, it adds the "first" class to the first

tag and the "last" class to the last

tag. Finally, it outputs the modified array with the added classes.

Rate this post

4 of 5 based on 8331 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us