dqhendricks
dqhendricks

Reputation: 19251

Having problems getting a PHP regex to match

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?

Upvotes: 3

Views: 163

Answers (2)

thirtydot
thirtydot

Reputation: 228182

<?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.

Upvotes: 3

Sujith Surendranathan
Sujith Surendranathan

Reputation: 2579

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

Upvotes: 0

Related Questions