Link to home
Create AccountLog in
Avatar of Chris Stanyon
Chris StanyonFlag for United Kingdom of Great Britain and Northern Ireland

asked on

preg_replace_callback with square brackets

Hi,

Having a problem creating a regular expression to find and replace variable text within square brackets.

My string may contain several strings, wrapped in square brackets. The strings will be in the format of:

[brand:12:linkText]

I need to search for the text inside the square brackets, pass it to a function, and then replace the text (including the square brackets) with the return value of the function.

The code below returns the following error:

Delimiter must not be alphanumeric or backslash

Help !
$string = "This is a [brand:7:linkText] and so is [category:14:My Category]";

$pattern = "\[[a-zA-Z0-9:]\]"; //this isn't working

echo preg_replace_callback($pattern, "createLinks", $string);

function createLinks($matches) {
	return "<a href='{$matches[0]}'>{$matches[0]}</a>";
}

Open in new window

Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Your pattern needs terminators:
$pattern = "/\[[a-zA-Z0-9:]\]/"; //this isn't working
(by terminators I mean delimiters)
Try this.  You pattern needed a space to change the second item into a link.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>preg_replace_callback with square brackets</title>
</head>
<body>
<h1>preg_replace_callback with square brackets</h1>
<?php 
error_reporting(E_ALL);
$string = "This is a [brand:7:linkText] and so is [category:14:My Category]";

$pattern = "#(\[[a-zA-Z0-9: ]+\]+)#"; //this isn't working
//$pattern = "#(\[)|(\])#"; //this isn't working

echo preg_replace_callback($pattern, "createLinks", $string);

function createLinks($matches) {
        return "<a href='".$matches[0]."'>".$matches[0]."</a>";
        //return "..";
}
?>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Chris Stanyon

ASKER

Thanks guys for the quick response.

@TerryAtOpus - I'd already tried with the delimiters - similar to your answer, but no joy.

@DaveBaldwin - Spot on. Exactly what I was looking for. Your second example saves me that extra step in the function - removing the square brackets.



Cool, thanks for the points.