James
James

Reputation: 6008

Replace text double-wrapped in square braces with new text

this probably will be fairly simple, but how am I able to find all the matches using regex of this occurrence in a load of text.

[[data in here]]

EG:

Blah blah blah [[find]] and maybe [[this]]

So I am able to find the occurrences and then replace them as urls.

Does that make sense?

I tried using

preg_match_all("/[[([^<]*)]]/", $data, $matches, PREG_OFFSET_CAPTURE);

But returns errors.

Upvotes: 0

Views: 119

Answers (4)

Imagist
Imagist

Reputation: 18514

[ and ] have meaning in regular expression syntax. To match them, you need "escape" them using the \ character. So your regular expression would be:

"/\[\[(.+?)\]\]/"

The usage of the [ and ] characters and how to escape them is pretty basic regular expression knowledge. Not to be rude, but I suggest spending a little more time learning regular expressions before you write any for production code.

Upvotes: 0

too much php
too much php

Reputation: 90978

You need to escape the '[' and ']' characters - they are special characters in regex. You're probably best off doing this with preg_replace_callback()

function makeURL($matches) {
    $url = $matches[1];
    return "<a href=\"http://$url\">$url</a>";
}

$data = 'My website is [[www.example.com]].';

echo preg_replace_callback('/\[\[(.*?)\]\]/', 'makeURL', $data);

// output: My website is <a href="http://www.example.com">www.example.com</a>

You can tweak the makeURL() function to re-write the URL however you please.

Upvotes: 0

Alix Axel
Alix Axel

Reputation: 154513

Try this:

preg_match_all("/\[\[(.+?)\]\]/", $data, $matches, PREG_OFFSET_CAPTURE);

Upvotes: 5

Noon Silk
Noon Silk

Reputation: 55072

Maybe ....

"/\[.*\]/"

? Just a wild guess.

I think your basic problem is that you need to escape the '[]' brackets, as they are special chars.

Upvotes: 0

Related Questions