开发者

@ (at) symbols preg_replace function

Is the "@" symbol sometimes used to surround a PHP regular expression? I'm working with a code base and found this function call:

$content = preg_replace("@(</?[^>]*>)+@", "", $con开发者_运维技巧tent);

I believe it's removing all XML tags from the string but I'm not sure what the "@" symbol in there means.


Yes, it can be used to wrap the expression. The original author most likely does this because some (or several) expressions contain the "more traditional" / delimiter. By using @, you can now use / without the need to escape it.

You could use:

  • /pattern/flags (traditional)
  • @pattern@flags
  • $pattern$flags
  • etc.


The manual calls them the PCRE "delimiters". Any ASCII symbol (non-alphanumeric) can be used (except the null byte).

Common alternatives to / are ~ and #. But @ is just as valid.

PCRE also allows matching braces like (...) or <...> for the regular expression.


You can use nearly any punctuation character as a delimiter in PHP regular expressions. See the docs here. Usually, the / is the first choice (and I would have suggested its use here), but if your regex contains slashes, a different character can be useful.

Mostly, I've seen %...%, ~...~ and #...#, but @...@ is OK, too.


Short answer is yes. The specific symbol used isn't important; it should generally be something that doesn't appear within the pattern. For example, these are all equivalent:

<?php
    preg_replace("@(<\?[^>]*>)+@", "", $content);
    preg_replace("/(<\?[^>]*>)+/", "", $content);
    preg_replace("!(<\?[^>]*>)+!", "", $content);  
?>

The reason the symbol is necessary is because modifiers may be added after the expression. For example, to search case insensitive, you could use:

<?php
   preg_replace("@(<\?[^>]*>)+@i", "", $content);
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜