Victor Bjelkholm
Victor Bjelkholm

Reputation: 2016

Help with preg_match_all, remove square braces

I'm trying to make a function that take out the content in square braces but I can't remove the braces that I need to remove.

This is how it should look:

Hello [there] blabla

Turns into:

Hello <a href="http://blabla.com/index.php?id=there">linky</a> blabla

My current code:

$txt='Hello [there] blabla';

$re1='.*?'; # Non-greedy match on filler
$re2='(\\[.*?\\])'; # Square Braces 1

if ($c=preg_match_all ("/".$re1.$re2."/is", $txt, $matches))
{
    $sbraces1=$matches[1][0];
    print "<a href='http://blabla.com/index.php?id=$sbraces1'>Linky</a> \n";
}

My current code does this:

Hello [there] blabla

Turns into:

<a href='http://blabla.com/index.php?id=[there]'>Linky</a> 

Upvotes: 0

Views: 819

Answers (4)

Scott
Scott

Reputation: 3977

How about this?

EDIT:

<?php
$string = 'Hello [there] blabla';
$re2='(\\[)([^\\]]*)(\\])'; # Square Braces 1
$pattern = "/".$re2."/is";
$replacement = '<a href="http://blabla.com/index.php?id=$2">linky</a>';
echo preg_replace($pattern, $replacement, $string);
?>

Upvotes: 1

Gumbo
Gumbo

Reputation: 655489

Better use preg_replace preg_replace_callback with this pattern:

\[(.*?)\]

Here the part inside the brackets is grouped rather than the whole bracket with its content.

With preg_replace_callback you then can write a function that takes the match and turns it into a link:

function callback_linkify($match) {
    return '<a href="http://example.com/index.php?id='.urlencode($match[1]).'">Linky</a>';
}

And the use of that pattern and the callback function:

$output = preg_replace_callback('/\[(.*?)\]/', 'callback_linkify', $str);

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179176

If you'd like to match the square brackets and the inner content you can try using something like this:

"(\\[)([^\\]]*)(\\])"

I just hope I properly escaped the brackets.

Upvotes: 0

Joey
Joey

Reputation: 354694

Capture the part between the brackets in a backreference:

\[([^\]]*)\]

and then use the first backreference instead of the whole match in its place.

Upvotes: 0

Related Questions