Skip to content

Instantly share code, notes, and snippets.

@twfahey1
Created May 16, 2022 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twfahey1/4c6281d42f084132f137be30fa18f36e to your computer and use it in GitHub Desktop.
Save twfahey1/4c6281d42f084132f137be30fa18f36e to your computer and use it in GitHub Desktop.
Drupal + PHP - Markup manipulation - Weave text inside of the initial <p> tag of a text field
<?php
use Drupal\Component\Utility\Html;
// For example, we have a node with a "tracking ID" that we want to weave in as an image element to the first paragraph.
// This snippet will alter that markup so when we pass it through to whatever renderer,
// we've leveraged PHP built in XML editing to "weave" this snippet into the first <p> tag
$description = $some_node->body->value;
$tracking_markup = "<img src='whatever' />";
if (!empty($description)) {
// We might get wonky HTML, so we don't want the xml lib warnings to flood watchdog.
libxml_use_internal_errors(TRUE);
$html_dom = Html::load($some_node->body->value);
// This gets the p tags, but could do any other tag here.
$paragraphs = $html_dom->getElementsByTagName('p');
$first_paragraph = $paragraphs->item(0);
$first_paragraph_text_content = $first_paragraph->textContent;
$updated_paragraph_text = $html_dom->createDocumentFragment();
$updated_paragraph_text->appendXML('<p>' . $tracking_markup . $first_paragraph_text_content . '</p>');
$first_paragraph->parentNode->replaceChild($updated_paragraph_text, $first_paragraph);
$description = Html::serialize($html_dom);
// Manipulate as needed before passing to feed.
$description = str_replace("&#13;", "", $description);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment