How do I convert doashes to underscores?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jeddiki
    Contributor
    • Jan 2009
    • 290

    How do I convert doashes to underscores?

    Hi,

    I am trying to change dashes to underscores in text file.

    The reason is that I am having problems processing some xml tags
    so I want to change this <merchant-name> to <merchant_nam e>

    To do this I used this regex:

    Code:
    $pattern = '#<(\w+)-(\w+)>#';
    $replacement = '<$1_$2>';
    $source = preg_replace( $pattern, $replacement, $source, -1 , $count);
    But for some reason, nothing is changed

    Have I misunderstood something ?

    The idea is that <anything-here> gets changed to <anything_her e>

    There is data between the tags that should not be touched, it is just the tag
    names themselves that I want to change.

    In the file, there about 2000 tags which need changing.

    Can anyone see what I am doing wrong ?


    Thanks.
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    A part from the tag name, are the tags empty? Are there any attributes?

    You regular expression only matches a tag like:
    - <xxx-yyy>

    If it contains anything else, it will fail to match.
    - <xxx-yyy >
    - <xxx-yyy/>
    - <xxx-yyy key="value">

    To fix this, it needs to allow characters to trail the tag name
    [code=]$pattern = '#<(\w+)-(\w+)([^>]*)>#';
    $replacement = '<$1_$2$3>';[/code]

    Also note that if anything between the tag name and the closing > char contains a > char, this will cause a problem. (Like if the value of an attribute contains a > char.) - This is why it is recommended to use XML or HTML parsers to manipulate HTML rather than regular expressions. (HTML is not a "regular" markup.)

    Comment

    • objx
      New Member
      • Mar 2010
      • 1

      #3
      Try this one. I tested it and it worked on my computer:


      Code:
      $source = preg_replace('#<([^>\-]+)-([^>]+)>#mU', "<$1_$2>", $source, -1 , $count);

      Comment

      Working...