3

Here is my problem. It's probably a simple fix. I have a regex that I am using to replace a url BBCode. What I have right now that is not working looks like this.

<?php
$input_string = '[url=www.test.com]Test[url]';
$regex = '/\[url=(.+?)](.+?)\[\/url]/is';
$replacement_string = '<a href="$1">$2</a>';
echo preg_replace($regex, $replacement_string, $input_string);
?>

This currently outputs the original $input_string, while I would like it to output the following.

<a href="www.test.com">Test</a>

What am I missing?

14
  • 2
    Your Reyes is looking for /url yet your demo doesn't include it. Is that a typo? Commented Jan 1, 2011 at 23:43
  • 2
    What you are missing is that you should not parse structured languages with regular expressions. There are bbcode parsers for PHP available. Commented Jan 1, 2011 at 23:43
  • asside from the fact that there are bbcode PECL extensions available, are there any other reasons that i should not use regex to do this? Commented Jan 1, 2011 at 23:54
  • This rather famous answer is the reason - as @Tomalak said, "you should not parse structured languages with regular expressions". If regex works for you in your situation, then it's fine, but regexes aren't generally a robust tool to use to parse "structured languages". Commented Jan 1, 2011 at 23:57
  • 1
    The point is, for every sophisticated smug regex you come up with, there will be a comparatively easy attack to knock it over. The problem of parsing bbcode is solved, why do want to roll you own parser? Bit-by-bit your regexes will become bloated, brittle and unmaintainable monsters with every corner case you work into them, and in the end it still won't be 100% safe. Apart from that, in terms if grammar complexity, bbcode is just like HTML, only with square brackets. Commented Jan 2, 2011 at 9:14

2 Answers 2

3
<?php
$input_string = '[url=www.test.com]Test[/url]';
$regex = '/\[url=(.+?)\](.+?)\[\/url\]/is';
$replacement_string = '<a href="$1">$2</a>';
echo preg_replace($regex, $replacement_string, $input_string);
?>
  • In your BBCode string, I closed the [url] properly.
  • I escaped a ] in the regex (not sure if that was an actual problem).

Note that [url]http://example.org[/url] is also a valid way to make a link in BBCode.

You should listen to the comments suggesting you use an existing BBCode parser.

Sign up to request clarification or add additional context in comments.

Comments

0

Change this line as follows: $regex = '/[url=(.+?)](.+?)[url]/is';

OK, the formatting is not proper. While I figure it out, see this: http://pastebin.com/6pF0FEbA

1 Comment

Dam*ed backslahes. I posted @ Pastebin. It works, but I could not paste it properly here :-/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.