Chris Stanyon
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 !
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>";
}
(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>
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
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.
@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.
$pattern = "/\[[a-zA-Z0-9:]\]/"; //this isn't working