tags:

views:

69

answers:

4

Guys, 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. Any ideas? :)

A: 

Maybe ....

"/\[.*\]/"

? Just a wild guess.

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

Noon Silk
+4  A: 

Try this:

preg_match_all("/\[\[(.+?)\]\]/", $data, $matches, PREG_OFFSET_CAPTURE);
Alix Axel
Fantastic, thank you.
James
Is there an advantage to using .+? over .* or is it just preference? I can't think of a situation where they would differ.
camomileCase
.* = matches any character, 0 or more times, as many times as possible
Alix Axel
.+? = matches any character, 1 or more times, as few times as possible
Alix Axel
Interesting. So will they capture different text, or is it just that your version isn't greedy and is presumably less expensive?
camomileCase
A: 

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\"&gt;$url&lt;/a&gt;";
}

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

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

// output: My website is <a href="http://www.example.com"&gt;www.example.com&lt;/a&gt;

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

too much php
A: 

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

Imagist