By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,696 Members | 2,213 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,696 IT Pros & Developers. It's quick & easy.

unexpected preg_replace behavior

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.