Thul
Thul

Reputation: 47

math with preg_replace captures

Im trying to convert XML to HTML, here part of the XML im trying to parse
<entry morerows="1">data 1</entry>
<entry morerows="2">data 2</entry>
<entry morerows="3">data 3</entry>
<entry morerows="4">data 4</entry>

This is supposed to turn into
<td rowspan="2">data 1</td>
<td rowspan="3">data 2</td>
<td rowspan="4">data 3</td>
<td rowspan="5">data 4</td>

I'v tried the following code without much success:
$content = preg_replace('/<entry morerows="([\d]+?)">/', '<tr '.('$1' + 1).'>' ,$content);

Im unable to calculate with the capture group, so my question is how can i capture the "morerows" attribute value AND add 1 to that value and replace the current value with that. The number of <entry> tags can be between 1 and 255.

Upvotes: 2

Views: 1055

Answers (3)

mario
mario

Reputation: 145482

Besides the /e modifier you must also rewrite the replacement part into a true expression.

 preg_replace('/<entry morerows="([\d]+?)">/e',
              '   "<tr rowspan=" . ("$1" + 1) . ">"   ',

Note that the single quotes enclose the whole expression. Within double quotes are used (for readability) to construct another string. The extraneous whitespace is in PHP context, only strings within double quotes become result data.

Upvotes: 4

Colin Fine
Colin Fine

Reputation: 3364

You need to give the 'e' modifier to the pattern in preg_replace in order to put code in the replacement rather than text.

Upvotes: 0

TML
TML

Reputation: 12966

You have to use the /e modifier to accomplish this (see this codepad example - note the use of htmlentities() to make the visual display more obvious). However, looking at your code here, it seems unlikely that your question will actually do what you want - <td rowspan="2">data 1</td> followed by <td rowspan="3">data 2</td> isn't likely to do anything very appealing - you'll usually want to skip the rowspanning column in subsequent rows. I recommend looking into XSL instead, which will give you a much more flexible language for performing this kind of markup matching and rewriting - see PHP's XSL documentation for more.

Upvotes: 1

Related Questions