开发者

eregi_replace("[\]",'',$data) -- what does this line do?

In the latest phpmailer开发者_如何学Python example file, there's the following line:

$body = eregi_replace("[\]",'',$body);

As I'm not really good in regular expressions, I can't figure out what the above does and whether I need to use it when I write my own block of data ($body). Could anyone help me figure this out?

EDIT

I really copied it properly. Here is a whole chunk of code from the original phpmailer example file, completely untouched:

require_once('../class.phpmailer.php');

$mail             = new PHPMailer(); // defaults to using php "mail()"

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");

$mail->SetFrom('name@yourdomain.com', 'First Last');


That code is removing all backslashes from $body.

Though it may look a little odd at first glance, the regex is correct. The backslash isn't a metacharacter when it's inside brackets in a POSIX regex.

There's all sorts of problems with this code anyway, though, especially since it's supposed to be an example:

  • It uses one of the deprecated ereg (or POSIX) family of regex functions. Half-recent PHP examples should pretty much all be using the preg (Perl-compatible) family instead.
  • It uses case-insensitive matching (the i in eregi) even though it's not matching against any letters, so case is irrelevant.
  • Most importantly, the actual purpose of the replacement is unclear. I can only guess that this is a misguided attempt to account for PHP's magic quotes feature that automatically adds backslashes to all sorts of things.

    To be clear, this code is not a proper way to deal with magic quotes, since it will remove all backslashes from $body, even "real" ones present in the original input. The stripslashes() function is intended for exactly this use case. Or, since the example deals with reading from a file, you could simply turn off magic quotes.


The code removes all backslahses.

Just try out the code on some sample input.

I'm not sure why eregi was chosen, since it and its brethren have been deprecated. Better to use preg_replace().

Note that eregi_replace() and preg_replace() have different usage rules. The first uses the POSIX regex extension while the later uses the PCRE functions. Here's a list of the differences, which are what makes understanding your code difficult if you assume preg_replace() syntax.

These all do the same thing:

eregi_replace("[\]",'',$body);  \\ Remove backslashes with POSIX regexes

preg_replace("[\\\]",'',$body);   \\ Remove backslashes with PCRE regexes
preg_replace("/[\\\]/",'',$body); \\ Ditto
preg_replace("/\\\/",'',$body);   \\ Ditto
preg_replace("*\\\*",'',$body);   \\ Ditto

Further reading.


This "[\]" means that you are escaping the left-pointed tag ]...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜