1

I'm trying to match any open HTML tag except input tag using regular expression in PHP. Here is my pattern.

/<([a-z]+)([^>]*>)?/i

It matches all below:

<input type="text">
<img src=">
<a href="">
<button type="button"></button>
<div id="some"></div>
<p></p>

I don't want to match input. I may exclude more tags in the future as I stated some tags in my question title.

What I've tried so far

[Edit]

As per my example, I also want to keep the tag name only returned in the matched results, e.g, img, a, button, div, p, etc.

3
  • Add a negative assertion. Commented Jan 2, 2015 at 13:48
  • 1
    Obligatory: stackoverflow.com/questions/1732348/… Commented Jan 2, 2015 at 14:02
  • 2
    Don't use regular expressions to parse HTML. Use a proper HTML parsing module. You cannot reliably parse HTML with regular expressions, and you will face sorrow and frustration down the road. As soon as the HTML changes from your expectations, your code will be broken. See htmlparsing.com/php or this SO thread for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged. Commented Jan 2, 2015 at 15:33

2 Answers 2

2
<(?:(?!input)[^>])*>(?:<\/[^>]*>)?

Try this.See demo.

https://www.regex101.com/r/fG5pZ8/13

$re = "/<(?:(?!input)[^>])*>(?:<\\/[^>]*>)?/im";
$str = "<input type=\"text\">\n<img src=\">\n<a href=\"\">\n<button type=\"button\"></button>\n<div id=\"some\"></div>\n<p></p>";

preg_match_all($re, $str, $matches);

Edit:

Use

(?!<input)<([A-Z0-9a-z]+)([^>]*>)?

If you want to save tag separately.

https://www.regex101.com/r/fG5pZ8/16

Sign up to request clarification or add additional context in comments.

Comments

2

Use a negative lookahead like (?!input\b):

<(?!input\b)([\w]+)([^>]*>)?

To exclude multiple tags, use (?!(?:tag1|tag2|tag3|...)\b)

1 Comment

Now OP says he does not want inputasd.newaz urs is correct as per OP's original question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.