PHP/RegExp: Escaping forward slash

tenx23

New Member
Messages
25
Reaction score
0
Points
0
Hello,

I am having trouble with my Regular Expression I'm using to make a BBcode system.

I can't seem to be able to escape the forward slash.

Here is the preg pattern I have:

Code:
/\[a\](.*?)\[\/a\]/i
It doesn't like the \/a and comes up with unknown modifier 'A'.


Help please!

Thanks,
tenx23
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
PHP:
<?php 

$patt = '/\[a\](.*?)\[\/a\]/i' ;

$hay = 'foo and [A]something here[/a] past the match';

$res = preg_match_all( $patt, $hay, $matches ) ;

echo $matches[ 0 ][0] ;
echo "   <br />\n" ;
echo $matches[ 1 ][0] ;

Works as expected with no errors.

Posting just a snippet as you did removes it from the context where there might be other errors. It is always best to post all of the relevant code.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Note that you don't need to use forward slashes as delimiters. Pick a different delimiter and you don't need to escape the slash.

PHP:
preg_match('%\[a\](.*?)\[/a\]%i', '', '')

However, regular expressions aren't terribly suited for parsing context-free languages such as BBCode. If someone were to nest [a] elements, it will break your parser. It's not as bad as parsing HTML with regexes, but REs still aren't the correct tool.

Unless you're doing this for your own education, use an existing BBCode library, such as PHP's built-in bbcode extension. Otherwise, you'll find yourself making more mistakes (such as parsing with regexes), which is fine when learning but not for production systems. If you need features not present in existing libraries, you can extend one rather than starting from scratch.
 
Top