preg_replace problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • zorro

    preg_replace problem

    i just don't get...this prints nothing:

    echo preg_replace("/(.*)(\d*)(.*)/","$2","the price is $33 dollars");

    I've been using these kind of regexes for several months, usually I
    expect it should print 33.
    Could some php configuration have changed somehow?
  • John Dunlop

    #2
    Re: preg_replace problem

    zorro wrote:
    [color=blue]
    > i just don't get...this prints nothing:
    >
    > echo preg_replace("/(.*)(\d*)(.*)/","$2","the price is $33 dollars");
    >
    > I've been using these kind of regexes for several months, usually I
    > expect it should print 33.[/color]

    The Kleene star ('*') is, by default, greedy. In other
    words, it matches zero or more of whatever came before while
    the rest of the pattern still matches. Your first
    subpattern matches the entire subject string, and so the
    others match nothing.

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.


    --
    Jock

    Comment

    • Daniel Andersen

      #3
      Re: preg_replace problem

      zorro wrote:
      [color=blue]
      > i just don't get...this prints nothing:
      >
      > echo preg_replace("/(.*)(\d*)(.*)/","$2","the price is $33 dollars");
      >
      > I've been using these kind of regexes for several months, usually I
      > expect it should print 33.
      > Could some php configuration have changed somehow?[/color]

      I think the problem is that PHP regexes use \2 to represent the second
      matched pattern rather than $2. If you change the second argument to '\2'
      you should be fine i think.

      Daniel

      Comment

      • gilm

        #4
        Re: preg_replace problem


        Daniel Andersen wrote:[color=blue]
        > zorro wrote:
        >[color=green]
        > > i just don't get...this prints nothing:
        > >
        > > echo preg_replace("/(.*)(\d*)(.*)/","$2","the price is $33[/color][/color]
        dollars");[color=blue][color=green]
        > >
        > > I've been using these kind of regexes for several months, usually I
        > > expect it should print 33.
        > > Could some php configuration have changed somehow?[/color]
        >
        > I think the problem is that PHP regexes use \2 to represent the[/color]
        second[color=blue]
        > matched pattern rather than $2. If you change the second argument to[/color]
        '\2'[color=blue]
        > you should be fine i think.
        >
        > Daniel[/color]

        this will work :

        echo preg_replace("/^(\D+)(\d+)(\D+ )$/","\\2","th e price is $33
        dollars");

        Comment

        Working...