Forum Moderators: coopster

Message Too Old, No Replies

Quick Regular Expression Question

         

sebflipper

6:38 pm on Feb 12, 2007 (gmt 0)

10+ Year Member



How can I convert a string say:
<itunes:image href="http://www.domain.com/images/pic.jpg" />

To:
<itunes:image>http://www.domain.com/images/pic.jpg</itunes:image>

Using Regular Expression?

I have looked through regular expression tutorials and tried writing a small demo script, but I just can't seem to get my head around it, at all as everything I have tried just results in errors!

Any help would be much appreciated!

whoisgregg

6:48 pm on Feb 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm not a regex guru so I'm often forced to find less sophisticated solutions. Perhaps these two str_replace functions will do the trick?

$original = '<itunes:image href="http://www.domain.com/images/pic.jpg" />';
$converted = str_replace( ' href="', '>', $original);
$converted = str_replace( '" />', '</itunes:image>', $converted);
echo $converted; // <itunes:image>http://www.domain.com/images/pic.jpg</itunes:image>

sebflipper

7:16 pm on Feb 12, 2007 (gmt 0)

10+ Year Member



Problem is that my string is an entire XML document/podcast.

I did try using the basic search and replace before, but this command:
$converted = str_replace( '" />', '</itunes:image>', $converted);

Ended up breaking the XML page, by removing all the ending tags on the rest of the tags in the XML document.

cameraman

7:39 pm on Feb 12, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could use explode to separate it from the group first:
$parts = explode($original,'/>',2); // last parameter limits it to one explosion (2 parts).
$parts[0] .= '/>'; // Explode will swallow the delimiter, so put it back on the first part

Then perform the above posted operations on $parts[0]. The remainder of the document will be waiting for you unharmed in $parts[1].

sebflipper

8:15 pm on Feb 12, 2007 (gmt 0)

10+ Year Member



Problem again with:
$converted = str_replace( '<itunes:image href="', '<itunes:image>', $original);

$parts = explode('" />', $converted, 2); // last parameter limits it to one explosion (2 parts).
$parts[0] .= '</itunes:image>'; // Explode will swallow the delimiter, so put it back on the first part

$final = implode('', $parts);

echo $final;

Is because that's applied to the whole XML/podcast it affecting XML tags ending with

" />
before <itunes:image href="http://www.domain.com/images/image.jpg" /> appears.

eelixduppy

8:29 pm on Feb 12, 2007 (gmt 0)



Try something like this, going back to regex ;)

$pattern = "/<itunes:image href=\"([^\"]+)\" \/>/i";
$replace = "<itunes:image>\\1</itunes:image>";
echo [url=http://us3.php.net/preg-replace]preg_replace[/url]($pattern, $replace, $string);

More info here:Pattern Syntax [us3.php.net]

Good luck!

sebflipper

10:37 pm on Feb 12, 2007 (gmt 0)

10+ Year Member



Cheers for that, fixed it like a treat!