Doodled
Doodled

Reputation: 180

php regex preg_match less than character breaking code

I'm trying to put together a preg_match to spot the following pattern

<[alphanumericstring] id[space or nospace]=[space or nospace][doublequotes or single quotes]a text string[doublequotes or single quotes][space or nospace]>

So the code will recognise: and

This works: if (preg_match("/[a-z0-9] id\s*=\s*[\"\']".$variable."\s*[\"\']\s*>/i", $document_content))

But it stops working as soon as I add the first '<' like this: if (preg_match("/<[a-z0-9] id\s*=\s*[\"\']".$variable."\s*[\"\']\s*>/i", $document_content))

I've tried it as < as well. The final '>' doesn't cause any issues but is there some special way the '<' should be entered?

Upvotes: 2

Views: 948

Answers (2)

Steven Moseley
Steven Moseley

Reputation: 16325

A few notes:

  1. For spaces use an actual space ( ) character. \s will match tabs and line-breaks, too
  2. Use ? for optional (1 or 0 instances). * means 0 or more instances
  3. Escape your tag open/close. PCRE supports named params using LT/GT syntax.

Try this:

<?php
if (preg_match("/\\<[a-z0-9]+ id ?= ?[\"']{$variable} ?[\"'] ?\\>/i", $document_content))

Upvotes: 1

Philipp Molitor
Philipp Molitor

Reputation: 387

/\<[a-z0-9]+\sid\s?\=\s?(?:'|")$YOUR_VARIABLE_STRING(?:'|")\s?\>/g

Try using this one. ( Made with http://regexr.com/ )

Upvotes: 0

Related Questions