unexpected preg_replace behavior

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

    unexpected preg_replace behavior

    say i have the following script:

    <?
    $test = "aaaaa";
    print '"' . preg_replace('/.*/','x',$test) . '"<br>';
    $test = "\n\n\n\n\n ";
    print '"' . preg_replace('/.*/','x',$test) . '"';
    ?>

    the output i would expect is as follows:

    "x"<br>"x"

    the output i actually get follows:

    "xx"<br>"x
    x
    x
    x
    x
    x"

    so why the difference? why do i get two x's instead of one x for the
    first preg_replace, and why does the preg_replace for the new line
    characters not give me the same thing as the first preg_replace?
  • Pedro Graca

    #2
    Re: unexpected preg_replace behavior

    yawnmoth wrote:[color=blue]
    > say i have the following script:
    >
    > <?
    > $test = "aaaaa";
    > print '"' . preg_replace('/.*/','x',$test) . '"<br>';[/color]

    Somehow preg_replace breaks "aaaaa" into "aaaaa" and "" (the empty
    string). I checked with

    $n = preg_match_all( '/.*/', $test, $matches);
    echo $n, ' matches: '; print_r($matche s);

    I couldn't find a modifier to stop that behaviour, but maybe you can
    change your preg_replace to

    preg_replace('/.+/', 'x', $test)

    matching 1 or more characters instead of 0 or more.
    [color=blue]
    > $test = "\n\n\n\n\n ";
    > print '"' . preg_replace('/.*/','x',$test) . '"';[/color]

    The regular expression "." does not match "\n" unless you say so with
    the "/s" modifier

    preg_replace('/.*/s', 'x', $test)

    Like this (with "*") it will match twice: for "\n\n\n\n\n " and ""
    Maybe you'd like to change the "*" to a "+" here too.
    [color=blue]
    > ?>
    >
    > the output i would expect is as follows:
    >
    > "x"<br>"x"
    >
    > the output i actually get follows:
    >
    > "xx"<br>"x
    > x
    > x
    > x
    > x
    > x"
    >
    > so why the difference? why do i get two x's instead of one x for the
    > first preg_replace, and why does the preg_replace for the new line
    > characters not give me the same thing as the first preg_replace?[/color]

    See above :)

    --
    USENET would be a better place if everybody read: | to email me: use |
    http://www.catb.org/~esr/faqs/smart-questions.html | my name in "To:" |
    http://www.netmeister.org/news/learn2quote2.html | header, textonly |
    http://www.expita.com/nomime.html | no attachments. |

    Comment

    Working...