views:

98

answers:

3

I'm very poor with regexps but this should be very simple for someone who knows regexps.

Basically I will have a string like this:

<if>abc <else>xyz

I would like a regexp so if the string contains <if> <else>, it splits the string into two parts and returns the two strings after <if> and <else>. In the above example it might return an array with the first element being abc, second xyz. I'm open to approaches not using regexps too.

Any thoughts?

A: 

The regular expression you are looking for is:

/<if>(.*)<\/else>(.*)/

You'd have a problem if there are multiple <else>'s, though. It can be edited depending on what you want the result to be.

Also note that this regular expression would work even if there is something before <if>.

In PHP, you'd want a code like the following:

<?php
$string = '<if>abc</else>xyz';
preg_match_all("/<if>(.*)<\/else>(.*)/", $string, $matches);
foreach($matches[0] as $value) 
  {
    echo $value;
  }
?>
Sinan Taifour
You have to escape `/` near else
RaYell
Sorry, missed it. Edited.
Sinan Taifour
+2  A: 
// $subject is you variable containing string you want to run regex on
$result = preg_match('/<if>(.*)<else>(.*)/i', $subject, $matches);

// $matches[0] has the full matched text
// $matches[1] has if part
// $matches[2] has else part

The /i at the end makes the search case sensitive to allow both <if><else> and <IF> <elSE>

RaYell
Do I need to set $matches with `$matches=array();` before calling this? What will happen if the string doesn't contain <if> <else> and I try to access $matches after calling this line?
Click Upvote
To answer my own question above, $matches is set to just an empty array() if the `<if> <else>` isn't found
Click Upvote
+1  A: 

Regular Expressions will work for this in simple cases. For more complicated cases (where nesting occurs), you may find it easier to parse the string and use a simple stack to grab the data you need.

Nick Presta