digitalecartoons Posted June 15, 2008 Share Posted June 15, 2008 Reading it again still puzzles me. Let’s start by implementing tags that create boldface and italic text. Let’s say we want [ B ] to begin bold text and [EB] to end bold text. Obviously, we must replace [ B ] with <strong> and [EB] with </strong>.2 Achieving this is a simple application of eregi_replace:3 $joketext = eregi_replace('\\[ b ]', '<strong>', $joketext); $joketext = eregi_replace('\\[eb]', '</strong>', $joketext); Notice that, because [ normally indicates the start of a set of acceptable characters in a regular expression, we put a backslash before it in order to remove its special meaning. As backslashes are also used to escape special characters in PHP strings, we must use a double backslash for each single backslash that we wish to have in the regular expression. Without a matching [, the ] loses its special meaning, so it doesn’t need to be escaped, although you could put a (double) backslash in front of it as well if you wanted to be thorough. I get it that the [ must be escaped by a backslash, but why would double backslashes be necessary here? This should work the same: $joketext = eregi_replace('\[ b ]', '<strong>', $joketext); The single backslash sees to it that [ b ] is taken literally and not as a regex code only allowing 'b'. What am I missing? (ps, the [ b ] should be without the spaces before/after the b, but that's a bold code in here) Quote Link to comment https://forums.phpfreaks.com/topic/110281-double-backslashes/ Share on other sites More sharing options...
Daniel0 Posted June 15, 2008 Share Posted June 15, 2008 I get it that the [ must be escaped by a backslash, but why would double backslashes be necessary here? It wouldn't. The author of the text you quoted doesn't know what s/he is talking about. It's only necessary if adding a backslash would result in a valid escape sequence (e.g. \n is a newline and \t is a tab character). Moreover, that's only necessary for double quoted strings and strings using the HEREDOC syntax. The snippets in the quoted text, however, uses single quoted strings so it will be used verbatim without parsing escape sequences and without variable interpolation. See: http://php.net/manual/en/language.types.string.php for further information. Also, don't use the POSIX Regex Functions but use PCRE as they're faster. In this case it would be better to just use the regular str_replace() as it's even faster. Besides, the POSIX regex functions will be moved to PECL in PHP 6 if I remember correctly. Quote Link to comment https://forums.phpfreaks.com/topic/110281-double-backslashes/#findComment-565866 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.