-1

I have a simple regex im running in PHP, and for some reason it wont work with the opening bracket. See:

 $str = 'sdfsf sdfs<link rel="stylesheet" id="editor-buttons-css" href="http://localhost/wordpress/wp-includes/css/editor.min.css?ver=3.6" type="text/css" media="all">sdfsd sdfsdl';

    $reg = '/<link[\s\S]+eet/';
      preg_match($reg, $str, $re);
      print_r($re);
    // outputs: Array ( [0] => );

 $str = 'sdfsf sdfs<link rel="stylesheet" id="editor-buttons-css" href="http://localhost/wordpress/wp-includes/css/editor.min.css?ver=3.6" type="text/css" media="all">sdfsd sdfsdl';

    $reg = '/link[\s\S]+eet/';
      preg_match($reg, $str, $re);
      print_r($re);
    // outputs: Array ( [0] => link rel="stylesheet );

How can I get the regex to work with the opening bracket?

levi
  • 23,693
  • 18
  • 59
  • 73
  • 3
    it would be best if you didn't use REGEX for parsing HTML: http://stackoverflow.com/a/1732454/390819 – Cristian Lupascu Sep 11 '13 at 21:44
  • 2
    Your question doesn't make much sense. Can you read it and try writing it again? – Rottingham Sep 11 '13 at 21:44
  • **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 http://htmlparsing.com/php or [this SO thread](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged. – Andy Lester Sep 12 '13 at 01:03
  • @w0lf: Please don't post links to that question, because they are not helpful to the reader, unless you follow it up with something that is an answer they can use. *You* know the point of the comment and that wall of text is that parsing HTML with regexes is a bad idea. However, to someone else who is asking, that is not at all clear. Worse, it doesn't point the reader to any useful solutions that *can* help parse HTML reliably. – Andy Lester Sep 12 '13 at 01:04
  • I should clarify, I dont intend on doing any serious parsing. This is just a one time gig, where I need to extract a stylesheet from a blob of text. – levi Sep 12 '13 at 02:14
  • @AndyLester you're right, I'll keep that in mind. – Cristian Lupascu Sep 12 '13 at 07:29

1 Answers1

1

actually it output

Array ( [0] => <link rel="stylesheet ) 

but browser parse the html, try echo htmlspecialchars(print_r($re,true));

po_taka
  • 1,816
  • 17
  • 27