468,484 Members | 2,095 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,484 developers. It's quick & easy.

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?
Jul 17 '05 #1
1 1915
yawnmoth wrote:
say i have the following script:

<?
$test = "aaaaa";
print '"' . preg_replace('/.*/','x',$test) . '"<br>';
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($matches);

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.
$test = "\n\n\n\n\n";
print '"' . preg_replace('/.*/','x',$test) . '"';
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.
?>

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?


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. |
Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Margaret MacDonald | last post: by
3 posts views Thread by Charles | last post: by
7 posts views Thread by Dave Hansen | last post: by
6 posts views Thread by comp.lang.php | last post: by
9 posts views Thread by Jeff Louie | last post: by
62 posts views Thread by ashu | last post: by
2 posts views Thread by Dimitri Furman | last post: by
reply views Thread by theflame83 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.