Skip to content
The Chat Archive
claude-2.1· Anthropic Arena Human Preference 55K

I get data from a CMS which uses tinymce. In my PHP coding I need to wrap the HTML text…

  1. User

    I get data from a CMS which uses tinymce. In my PHP coding I need to wrap the HTML text coming from the CMS inside a p with a callss. However, the content seems to already be wrapped inside a p and apparently Text is not valid valid HTML. How can I fix this? Code looks like this:

  2. Assistant

    To avoid nested <p> tags, you can check if the content is already wrapped in a <p> tag before wrapping it again.

    Here is one way to do it:

    <?php
    
    if(!empty($recordData['text'])) {
    
      $text = $recordData['text'];
      
      if (strpos($text, '<p>') === false) {
        $text = '<p class="small">' . $text . '</p>';
      }
      
      echo $text;
    
    }
    
    ?>
    

    This checks if <p> exists in the text using strpos(). If not, it will wrap the text in a <p> tag with the class.

    Alternatively, you could use DOMDocument to manipulate the HTML more robustly:

    $doc = new DOMDocument();
    $doc->loadHTML($recordData['text']);
    
    $paragraphs = $doc->getElementsByTagName('p');
    if($paragraphs->length == 0) {
      $p = $doc->createElement('p');
      $p->setAttribute('class', 'small');
      $doc->appendChild($p); 
    } else {
      $p = $paragraphs->item(0);
    }
    
    echo $doc->saveHTML($p);
    

    This loads the HTML, gets any existing <p> tags, and adds the class to the first one if needed.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt