0

I am trying to parse a string of HTML tag attributes in php. There can be 3 cases:

attribute="value"  //inside the quotes there can be everything also other escaped quotes
attribute          //without the value
attribute=value    //without quotes so there are only alphanumeric characters

can someone help me to find a regex that can get in the first match the attribute name and in the second the attribute value (if it's present)?

8
  • 9
    Why are you trying to do this with a regular expression? A real HTML parser is a much easier approach. Commented Sep 4, 2009 at 15:47
  • Because i'm building my own library and i can't take the code from another one Commented Sep 4, 2009 at 15:49
  • 2
    because i want to do it like this Commented Sep 4, 2009 at 15:57
  • 2
    You mean you want us to tell you how to use a glass bottle for pounding your nails? weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/… Commented Sep 4, 2009 at 16:00
  • 1
    @mck89: please, don't feel attacked, it wasn't my intention. Its just that you are going through the this the hard way. Didn't attempt to offend you, just wanted to know why you couldn't use neither existing code nor an html parser. Commented Sep 4, 2009 at 16:03

2 Answers 2

9

Never ever use regular expressions for processing html, especially if you're writing a library and don't know what your input will look like. Take a look at simplexml, for example.

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

Comments

2

Give this a try and see if it is what you want to extract from the tags.

preg_match_all('/( \\w{1,}="\\w{1,}"| \\w{1,}=\\w{1,}| \\w{1,})/i', 
    $content, 
    $result, 
    PREG_PATTERN_ORDER);
$result = $result[0];

The regex pulls each attribute, excludes the tag name, and puts the results in an array so you will be able to loop over the first and second attributes.

2 Comments

I found a faster and more precise solution, but i try your regex and it seems to work so it's a good starting point and i take your answer as solution. Thank you!

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.