Cara menggunakan php regex remove tag

In this article, we will see how to remove HTML tags from data in PHP. PHP provides an inbuilt function to remove the HTML tags from the data. The strip_tags() function is an inbuilt function in PHP that removes the strings form HTML, XML and PHP tags. It accepts two parameters. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.

Syntax:

strip_tags(string, allowed_tags)

Parameters Values:

  • string: It is a required parameter that specifies the string to check.
  • allowed_tags: It is an optional parameter that specifies the allowable tags which will not be removed from the returned result.

Return Value: It returns a string where HTML tags are removed except for the allowed tags.

Example 1: In this example, we passed a string containing HTML tags to the strip_tags() function and checked the returned string whether all HTML tags are removed or not.  All the HTML tags in the string are stripped from the string by the strip_tags() function.

PHP




<?php

    echo strip_tags(

          "<b>GeeksforGeeks</b> one of the popular 

            <i>online learning site</i>");

<?php0

Output:

Cara menggunakan php regex remove tag

 

Example 2: In this code, we specified the allowed_tags parameter along with the string to strip_tags() method, so that we can allow a few tags in the string and strip the unallowed tags from the input string. In the allowed_tags section, we specified

tag. So it did not strip the

tag in the string and stripped the rest of the other tags i.e. italic tag.

I spent a while replacing all my ereg() calls to preg_match(), since ereg() is now deprecated and will not be supported as of v 6.0.

Just a warning regarding the conversion, the two functions behave very similarly, but not exactly alike. Obviously, you will need to delimit your pattern with '/' or '|' characters.

The difference that stumped me was that preg_replace overwrites the $matches array regardless if a match was found. If no match was found, $matches is simply empty.

ereg(), however, would leave $matches alone if a match was not found. In my code, I had repeated calls to ereg, and was populating $matches with each match. I was only interested in the last match. However, with preg_match, if the very last call to the function did not result in a match, the $matches array would be overwritten with a blank value.

Here is an example code snippet to illustrate:

$test = array('yes','no','yes','no','yes','no');

foreach ($test as $key=>$value) {
  ereg("yes",$value,$matches1);
  preg_match("|yes|",$value,$matches2);
}
  print "ereg result: $matches1[0]
";
  print "preg_match result: $matches2[0]
";
?>

The output is:
ereg result: yes
preg_match result:

($matches2[0] in this case is empty)

I believe the preg_match behavior is cleaner. I just thought I would report this to hopefully save others some time.

In many countries the numeric format is 1.000,33 in english it is 1,000.33

This function converts numeric arguments always into the PHP confirm numeric format. If only one seperator is into the numericstring so it is interpreted as the decimalpoint.

function dp($zahl)
{
  if ((strpos($zahl,".") > "-1") | (strpos($zahl,",") > "-1")) {
    if ((strpos($zahl,".") > "-1") & (strpos($zahl,",") > "-1")) {
      if (strpos($zahl,".") > strpos($zahl,",")){
          return str_replace(",","",$zahl);
    } else {
          return str_replace(",",".",str_replace(".","",$zahl));
      }
  } else {
      if (strpos($zahl,".") > "-1") {
        if (strpos($zahl,".") == strrpos($zahl,".")) {
            return $zahl;
      } else {
          return str_replace(".","",$zahl);
        }
    } else {
        if (strpos($zahl,",") == strrpos($zahl,",")) {
          return str_replace(",",".",$zahl);
      } else {
          return str_replace(",","",$zahl);
        }
    } }
} else {
    return $zahl;
} }

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.


Syntax

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.

In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~.


Regular Expression Functions

PHP provides a variety of functions that allow you to use regular expressions. The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly used ones:

FunctionDescriptionpreg_match()Returns 1 if the pattern was found in the string and 0 if notpreg_match_all()Returns the number of times the pattern was found in the string, which may also be 0preg_replace()Returns a new string where matched patterns have been replaced with another string

Using preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern.

Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
?>

Try it Yourself »


Using preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a string.

Example

Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string:

$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>

Try it Yourself »


Using preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another string.

Example

Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:

$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit W3Schools!"
?>

Try it Yourself »



Regular Expression Modifiers

Modifiers can change how a search is performed.

ModifierDescriptioniPerforms a case-insensitive searchmPerforms a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)uEnables correct matching of UTF-8 encoded patterns

Regular Expression Patterns

Brackets are used to find a range of characters:

ExpressionDescription[abc]Find one character from the options between the brackets[^abc]Find any character NOT between the brackets[0-9]Find one character from the range 0 to 9

Metacharacters

Metacharacters are characters with a special meaning:

MetacharacterDescription|Find a match for any one of the patterns separated by | as in: cat|dog|fish.Find just one instance of any character^Finds a match as the beginning of a string as in: ^Hello$Finds a match at the end of the string as in: World$\dFind a digit\sFind a whitespace character\bFind a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b\uxxxxFind the Unicode character specified by the hexadecimal number xxxx

Quantifiers

Quantifiers define quantities:

QuantifierDescriptionn+Matches any string that contains at least one nn*Matches any string that contains zero or more occurrences of nn?Matches any string that contains zero or one occurrences of nn{x}Matches any string that contains a sequence of X n'sn{x,y}Matches any string that contains a sequence of X to Y n'sn{x,}Matches any string that contains a sequence of at least X n's

Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. For example, to search for one or more question marks you can use the following expression: $pattern = '/\?+/';


Grouping

You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match.