Diego
Diego

Reputation: 3

A regular expression to extract text between two tags and ALSO the tag name

I need a simple markup language to store different parts of a string on a TEXT field, and then extract those parts. So basically I want some kind of simple XML. Storing those in the table field is easy, but extracting them... is other matter. I managed to do so using a simple regex done for regular HTML:

|<[^>]+>(.*)</[^>]+>|U

But in order to re-compose the original array (and use the markup more generally) I need also to know the tag names. And that regex does't do that.

Examples:

Input text:

<user_input>Hello! my name is Williams</user_input>

The preg_match_all() function using the above regex returns:

array
  0 => 
    array
      0 => string '<user_input>Hello! my name is Williams</user_input>' (length=34)

  1 => 
    array
      0 => string 'Hello! my name is Williams' (length=34)

I need it to return the "user_input" name of the tag. Yes, I know, I suck on regex. Yes, I know "use a XML parser", but that is too big for what I'am doing.

Upvotes: 0

Views: 1462

Answers (4)

Alan Moore
Alan Moore

Reputation: 75232

Just use a capturing group like you did with the content:

|<([^>]+)>([^<]*)</\1>|

As an added bonus, you can use the captured name to make sure the closing tag has the same name.

Upvotes: 1

meder omuraliev
meder omuraliev

Reputation: 186652

How is a xml parser "too big"? PHP has built-in native functions that allow you to do it easily.

Regex doesn't fit the job.

<?php

$string = '
<root>
<input_name>blah</input_name>
</root>
';

$x = new DOMDocument();
$x->loadXML($string);
$root = $x->documentElement;
$elements = $root->getElementsByTagName('*');
$count = count($elements->length);

for ( $i = 0; $i< $count; $i++ ) {
    $el = $elements->item($i);
    echo $el->nodeName . '<br>';
    echo $el->nodeValue . '<br>';
}

Upvotes: 6

Turtle
Turtle

Reputation: 1350

|<([^>]+)>(.*)</[^>]+>|U

Will do what you want. I merely added two parenthesis. It is a very brittle hack. You want to use a parser. Especially as you apparently don't understand regexps.

Upvotes: 0

Anon.
Anon.

Reputation: 59993

So basically I want some kind of simple XML

Then you want an XML parser. And hey, PHP has an XML parsing extension you can install.

Seriously, trying to hack your way there with regexes is only going to end in pain and frustration. Use an XML parser, and save yourself hours of work.

but that is too big for what I'am doing.

No, it's not. You're wanting to parse something - hence, you should use a parser.

Upvotes: 1

Related Questions