Bo Pennings
Bo Pennings

Reputation: 985

replace with string between pattern

I have a question. I want to read a wrong xml format with the php function simplexml_load_string but I get empty values because the format is worng. Part of the xml:

<column name="price"><![CDATA[184.95]]></column>
<column name="category"><![CDATA[Dames]]></column>
<column name="subcategory"><![CDATA[Schoenen]]></column>
<column name="stock"><![CDATA[1]]></column>

I need to replace it to this:

<price><![CDATA[184.95]]></price>
<category><![CDATA[Dames]]></category>
<subcategory><![CDATA[Schoenen]]></subcategory>
<stock><![CDATA[1]]></stock>

to read the xml feed properly. Is it possible to replace this with preg_match for example? And how?

Upvotes: 0

Views: 71

Answers (2)

Toto
Toto

Reputation: 91385

How about:

$str = preg_replace('#<column name="([^"]+)">(.+?)</column>#', '<$1>$2</$1>', $str); 

Upvotes: 1

Ryan
Ryan

Reputation: 1338

The below would do it, but I think you could probably do it with preg_replace, see this link: php preg_replace matches

preg_match_all('/<column name=\"([a-z]+)\">(.*)<\/column>/', $string, $matches);

$string = '';
foreach( $matches[1] as $key => $name )
{
    $string .= "<{$name}>{$matches[2][$key]}</{$name}>\n";
}

Upvotes: 0

Related Questions