Jump to content

search and replace question

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
7 replies to this topic

#1
jonnyfolk

jonnyfolk

    Newbie

  • Members
  • Pip
  • 9 posts
Hi,

I have an xml file which is not formatted in a convenient way.

I need to change the various references:

<col name="price">93147</col>

<col name="value">93147</col>


to


<price>93147</price>

<value>93147</value>


in perl I would use something like:


if ( $var =~ m|<col name="(.*?)">(.*?)</col>|g ) {

  $var =~ s|<col name=".*?">.*?</col>|<$1>$2</$1>|g;

}

(untested!)

What is the best way of tackling this in php?

#2
Feral

Feral

    Programmer

  • Members
  • PipPipPipPip
  • 162 posts
I would use the preg_replace function along with the same type of regular expressions that you would use in perl

#3
Bioshox

Bioshox

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 207 posts
I think you may have the wrong forum...

#4
jonnyfolk

jonnyfolk

    Newbie

  • Members
  • Pip
  • 9 posts
Sorry - is this not the php forum?

#5
Bioshox

Bioshox

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 207 posts
Oh, my appologies, I thought you said in Perl!

What exactly are you trying to do? If your trying to decalair the names of the colums by using <tags> this wont work,

<col name="price">93147</col>

<col name="value">93147</col>

What you have already done is the correct way of doing it.

#6
jonnyfolk

jonnyfolk

    Newbie

  • Members
  • Pip
  • 9 posts
Hi, thanks for your reply. I need the 1st example to end up as the second. There are many <col name= tags so I need the script to pick up the name and then replace with the new tags accordingly. I see preg_replace might be useful but how will I pick up the name tag?
sorry for my ignorance...

#7
Bioshox

Bioshox

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 207 posts
Could I see the rest of the script, code is good :3

#8
jonnyfolk

jonnyfolk

    Newbie

  • Members
  • Pip
  • 9 posts
$strXML = get_content($strURLtoGo);

outputs like I described above. If you know a bit of perl you'll understand what I'm after.
I need to search/replace on $strXML

Cheers

Solution:

$pattern = '/<col name="(.*?)">(.*?)<\/col>/';
$replacement = '<$1>$2</$1>';
echo preg_replace($pattern, $replacement, $strXML);

Edited by jonnyfolk, 03 March 2010 - 09:21 AM.
solution found (myself)