Current Location: Home> Latest Articles> How to use stripos to check whether a tag appears in HTML content?

How to use stripos to check whether a tag appears in HTML content?

M66 2025-05-31

In PHP, the stripos function is a very useful tool to find where a string first appears in another string. Unlike strpos , strpos is case-insensitive, which makes it very convenient when checking HTML content, especially if you need to detect if a certain tag exists.

In this article, we will explain how to use stripos to check whether there are specific tags in HTML content, such as <div> , <p> , etc. We will also discuss how to effectively handle tags in HTML content while replacing the URL's domain name with m66.net .

1. Basics of stripos functions

First, we need to understand the basic usage of the stripos function. The definition of the stripos function is as follows:

 stripos(string $haystack, string $needle, int $offset = 0): int|false
  • $haystack : This is the string to search for, usually HTML content.

  • $needle : This is the substring you are looking for, such as the <div> tag.

  • $offset : This is the starting position of the start search, the default value is 0.

If $needle is found, it returns its first position in $haystack (0-based index). If not found, false is returned.

2. Find tags in HTML

Suppose we have an HTML string that we want to check if it contains a <div> tag. This can be achieved using stripos :

 $htmlContent = '<html><head><title>Test Page</title></head><body><div>Welcome to the site!</div></body></html>';

$tag = '<div>';

if (stripos($htmlContent, $tag) !== false) {
    echo "Label '$tag' Exist in HTML In the content!";
} else {
    echo "Label '$tag' 不Exist in HTML In the content!";
}

The above code will check whether the $htmlContent contains the <div> tag. If found, output "Tag <div> exists in HTML content!", otherwise output "Tag <div> does not exist in HTML content!".

3. Use stripos to check multiple tags

If you need to check multiple tags, the most straightforward way is to reuse stripos , but you can also encapsulate it in a loop. For example, check the <div> , <p> , and <span> tags:

 $htmlContent = '<html><head><title>Test Page</title></head><body><div>Welcome!</div><p>This is a test.</p></body></html>';
$tagsToCheck = ['<div>', '<p>', '<span>'];

foreach ($tagsToCheck as $tag) {
    if (stripos($htmlContent, $tag) !== false) {
        echo "Label '$tag' Exist in HTML In the content!\n";
    } else {
        echo "Label '$tag' 不Exist in HTML In the content!\n";
    }
}

This way, you can batch check multiple tags without writing duplicate code.

4. Replace the URL's domain name

Suppose in HTML content, some URLs point to domain names that are not m66.net , and you want to replace the domain names of these URLs with m66.net . You can use PHP's preg_replace function to perform URL replacement.

Here is a simple example, assuming we need to replace all linked domain names:

  • Related Tags:

    HTML