PHP Check If String Contains HTML Tags Example Tutorial

Table of Contents

Share this Article
Reading Time: 3 minutes
172 Views

Inside this article we will see the concept i.e PHP Check If String Contains HTML Tags Example. Article contains the classified information about checking HTML tags in string values. Usually we know HTML tags contain the pair of angular brackets. So, we will use the concept of PHP function preg_match() for this.

The preg_match() function returns whether a match was found in a string.

If you are looking for an article which gives you the understanding of checking a string contains HTML Tag or not then this article will help you a lot for this.

Learn More –

Let’s get started.

Application Programming

Create a file index.php inside your localhost path. We will consider two examples to understand the concept in deep.

Example #1 (String with HTML Tag)

Open index.php and write this code into it.

<?php

$myString = "Hi <h3>Online Web Tutor</h3>, You are awesome!!!";

if (isHTML($myString)) {

    echo "There is a HTML Tag in String";
} else {

    echo "No HTML Tag in String";
}

function isHtml($string)
{
    return preg_match("/<[^<]+>/", $string, $m) != 0;
}

Output

There is a HTML Tag in String

Example #2 (String with No HTML Tag)

Open index.php and write this code into it.

<?php

$myString = "Hi Online Web Tutor, You are awesome!!!";

if (isHTML($myString)) {

    echo "There is a HTML Tag in String";
} else {

    echo "No HTML Tag in String";
}

function isHtml($string)
{
    return preg_match("/<[^<]+>/", $string, $m) != 0;
}

Output

No HTML Tag in String

We hope this article helped you to learn PHP Check If String Contains HTML Tags Example Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5