Isis
Isis

Reputation: 4666

PHP preg_match regular expression

$var = '<lang test=<php>string</php>><lang test2=before<php>inside</php>>'.
       '<lang test3=THIRD_WITHOUT_PHP_TAGS><lang test4>';
if (preg_match_all('#<lang (.*?)>#', $var, $gg))
{
    var_dump($gg[1]);
}

I get the dump:

array(2) {
  [0]=>
  string(9) "test=<php"
  [1]=>
  string(16) "test2=before<php"
}

But I want to get :

test=<php>string</php>

and

test2=before<php>inside</php>

and

test3=THIRD_WITHOUT_PHP_TAGS

and

test4

How to do it?

EDIT: I CHANGE THE $var AND ADD third expression

EDIT 2: ADEED the fourth expression without "="

Upvotes: 2

Views: 981

Answers (3)

Sebastian Schmidt
Sebastian Schmidt

Reputation: 1078

The easiest way would be

#<lang (\w+=[^<]*(<[^>]+>)?[^<]+(?(2)</[^>]+>))>#

The Regex checks if a tag is matched and only then checks for ending tag.

If you want to catch also the fourth argument, you need to use

#<lang (\w+(=[^<]*(<[^>]+>)?[^<]+(?(3)</[^>]+>))?)>#

Upvotes: 3

Pascal H.
Pascal H.

Reputation: 54

I would do it this way:

preg_match("/<lang (.*)>/i", $var, $gg)

Upvotes: -1

axelcoon
axelcoon

Reputation: 81

$var = '<lang test=<php>string</php>><lang test2=before<php>inside</php>>';
if (preg_match_all('#<lang (.*>)>#U', $var, $gg))
{
    var_dump($gg[1]);
}

Upvotes: 0

Related Questions