Donovant
Donovant

Reputation: 3161

PHP: Expression regular, sub the "<?" and "?>", how it does?

i would to know how match all tag less "<?" and "?>" For example:

"<?root?><abcd>"

I thought:

preg_match_all(/[^(<\?)(\?>)]+/, $str, $match);

but rsult is ["root", "abcd"] instead i wold like to be so ["<abcd>"]

Thanks'!

Upvotes: 1

Views: 79

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173642

I sure hope this is not HTML, but this will match angle bracket surrounded words without question marks in between:

/<\w+>/

If other than \w characters are allowed inside but no question marks:

/<[^>?]+>/

If question marks are allowed inside but only rejected when adjacent to angle brackets:

/<[^?].*?[^?]>/

However, the above will have the side effect that <b> will not be matched due to minimum length constraint.

Upvotes: 2

Kendall Frey
Kendall Frey

Reputation: 44374

<(?!\?).+?(?<!\?)>

That should do the trick.

Explanation:

<    -- A <
(?!  -- Not followed by: (See link 1 - Positive and Negative Lookahead)
  \? -- A ?
)
.+?  -- As few characters as necessary (See link 2 - Laziness Instead of Greediness)
(?<! -- Not preceded by: (See link 1 - Positive and Negative Lookbehind)
  \? -- A ?
)
>    -- A >
  1. Lookaround
  2. Repetition

IIRC, you would do this:

preg_match_all('/<(?!\?).+?(?<!\?)>/', $str, $match);

However, it isn't a good idea to parse HTML with a regex.

Upvotes: 3

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

That's trivial, but you're approaching it the wrong way. You should be matching what you want rather than not matching what you don't want. To match a tag, use a variation of this:

<\w+[^>\?]*>

Making it as specific as you need it. As long as \? isn't in the set of allowed characters in the tag, it should be fine. Also note that this will match tags with attributes.

Upvotes: 0

Related Questions