Add html tag in string php

This was a cool question because it promoted thought about the DoM.

I raised a question How do HTML Parsers process untagged text which was commented generously by @sideshowbarker, which made me think, and improved my knowledge of the DoM, especially about text nodes.

Below is a DoM based way of finding candidate text nodes and padding them with 'p' tags. There are lots of text nodes that we should leave alone, like the spaces, carriage returns and line feeds we use for formatting (which an "uglifier" may strip out).

loadHTML($html);             // build the DoM
$bodyNodes = $dom->getElementsByTagName('body');  // returns DOMNodeList object
foreach($bodyNodes[0]->childNodes as $child)      // assuming 1  node
{
    $text="";
    // this tests for an untagged text node that has more than non-formatting characters
    if ( ($child->nodeType == 3) && ( strlen( $text = trim($child->nodeValue)) > 0 ) )
    { // its a candidate for adding tags
        $newText = "

".$text."

"; echo str_replace($text,$newText,$child->nodeValue); } else { // not a candidate for adding tags echo $dom->saveHTML($child); } }

nodeTest.html contains this.

 


    

Hello World

First

Second

Third

fourth

Third

and the output is this.... I did not bother echoing the outer tags. Notice that comments and formatting are properly treated.

Hello World

First

Second

Third

fourth

Third

Obviously you need to traverse the DoM and repeat the search/replace at each element node if you wish to make the thing more general. We are only stopping at the Body node in this example and processing each direct child node.

I'm not 100% sure the code is the most efficient possible and I may think some more on that and update if I find a better way.

❮ PHP String Reference

Example

Strip the string from HTML tags:

echo strip_tags("Hello world!");
?>

Try it Yourself »


Definition and Usage

The strip_tags() function strips a string from HTML, XML, and PHP tags.

Note: HTML comments are always stripped. This cannot be changed with the allow parameter.

Note: This function is binary-safe.


Syntax

Parameter Values

ParameterDescription
string Required. Specifies the string to check
allow Optional. Specifies allowable tags. These tags will not be removed

Technical Details

Return Value:Returns the stripped string
PHP Version:4+
Changelog:As of PHP 5.3.4, this function ignores self-closing XHTML tags (like
) in allow parameter
As of PHP 5.0, this function is binary-safe.
As of PHP 4.3, HTML comments are always stripped.

More Examples

Example

Strip the string from HTML tags, but allow tags to be used:

echo strip_tags("Hello world!","");
?>

Try it Yourself »


❮ PHP String Reference


    Table of contents
  • Add html tag to string in PHP
  • Insert html tag in string in php
  • How to display HTML tags as plain text using PHP
  • Adding html tags to a string programmatically
  • How to add html span tag to the PHP date format
  • How to Use HTML Inside PHP on the Same Page

Add html tag to string in PHP

Hello World

First

Second

Third

Hello World

First

Second

Third

function htmlParser($html)
{
    foreach ($html->childNodes() as $node) {
        if ($node->childNodes()) {
            htmlParser($node);
        }
        // Ideally: add p tag to node innertext if it does not wrapped with any tag
    }

    return $html;
}
loadHTML($html);             // build the DoM
$bodyNodes = $dom->getElementsByTagName('body');  // returns DOMNodeList object
foreach($bodyNodes[0]->childNodes as $child)      // assuming 1  node
{
    $text="";
    // this tests for an untagged text node that has more than non-formatting characters
    if ( ($child->nodeType == 3) && ( strlen( $text = trim($child->nodeValue)) > 0 ) )
    { // its a candidate for adding tags
        $newText = "

".$text."

"; echo str_replace($text,$newText,$child->nodeValue); } else { // not a candidate for adding tags echo $dom->saveHTML($child); } }
 


    

Hello World

First

Second

Third

fourth

Third

Hello World

First

Second

Third

fourth

Third

function addPTag($html)
{
    $contents = preg_split("/(<\/.*?>)/", $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    foreach ($contents as &$content) {
        if (substr($content, 0, 1) != '<') {
            $chars = preg_split("/(<)/", $content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
            $chars[0] = '

' . $chars[0] . '

'; $content = implode($chars); } } return implode($contents); }
$stringHtml = 'Your received html';

$html = str_get_html(stringHtml);

//Find necessary element and edit it
$exampleText = $html->find('Your selector here', 0)->last_child()->innertext

Insert html tag in string in php

Mango
Orange
Banana


    
    
        ', 'Mango, Orange, Banana'); ?>
    




    


    ', $data);

        echo $data;
    ?>


How to display HTML tags as plain text using PHP

string htmlspecialchars( $string, $flags, $encoding, $double_encode )
string htmlentities( $string, $flags, $encoding, $double_encode )

Adding html tags to a string programmatically

 I need to put together a couple of functions that do the following:-
$string = 'This is a string.';
$first_letter = substr($string, 0, 1);
$remaining_string = substr($string, 1);

if(substr($string, 0, 5) != ''.$remaining_string;
}
if(substr($string, -7) != '') {
 $string .= '';
}
$string = 'This is a string.';

if(substr($string, 0, 5) != '
span.some_class:first-letter {
/* some styling */
}

How to add html span tag to the PHP date format

if ( ! function_exists( 'astra_post_date' ) ) {
    
    	/**
    	 * Function to get Date of Post
    	 *
    	 * @return html                Markup.
    	 */
    	function astra_post_date() {
    
    		$output        = '';
    		$format        = apply_filters( 'astra_post_date_format', 'j M' );
    		$time_string   = esc_html( get_the_date( $format ) );
    		$modified_date = esc_html( get_the_modified_date( $format ) );
    		$posted_on     = sprintf(
    			esc_html( '%s' ),
    			$time_string
    		);
    		$modified_on   = sprintf(
    			esc_html( '%s' ),
    			$modified_date
    		);
    		$output       .= '';
    		$output       .= '';
    		$output       .= ' ' . $modified_on . '';
    		$output       .= '';
    		return apply_filters( 'astra_post_date', $output );
    	}
    }

How to Use HTML Inside PHP on the Same Page





"
echo ""
$name="your name";
print $name;
echo "
" echo "" print $name; echo "" echo "" echo "" ?>
Name
'.$name.'
'; ?>

Next Lesson PHP Tutorial