I run a small auto-parts website with a custom cms. I use a bbcode style system to format text in text fields for part descriptions and whatnot. I want to add a new bbcode tag, the [part][/part] tag that, when wrapped around a part number, creates a link to the page with information about that part.
This way, I can say something like, "This part requires the use of this other part, #[part]ABC12345[/part]." Ideally, it should look up that part in the database and make a link to it if found. Otherwise, it should just show the part number.
To do so, I need to do a mysql search on that string... not something that you can do in a preg_replace without calling an external function. My problem is, within the bbpartsearch function, It does the query on the string "$1" (yes, a dollar sign followed by the number one), and not the part number which should get passed in.
What am I doing wrong here?
function bbpartsearch($part) {
require ("config.php");
$dbhandle = mysql_connect($DBHOST, $DBUSER, $DBPASS);
mysql_select_db($DBNAME, $dbhandle);
$query = "SELECT id FROM big_parts_list WHERE part_num='$part'";
$result = mysql_query($query) or die (mysql_error());
$num = mysql_numrows($result);
if ( $num == 0 ) {
return $part;
}
else {
$id = mysql_result($result, 0, 'id');
return '<a href="partinfo.php?id='.$id.'" class="partlink">'.$part.'</a>';
}
}
function bbcode ($string) {
$bbcode = array(
'#\[b\](.*?)\[/b\]#si' => '<b>\\1</b>',
'#\[i\](.*?)\[/i\]#si' => '<i>\\1</i>',
'#\[u\](.*?)\[/u\]#si' => '<u>\\1</u>',
'#\[url\](.*?)\[/url]#si' => '<a href="\\1" target="_blank" class="sm">\\1</a>',
'#\[img\](.*?)\[/img\]#si' => '<img src="\\1" border=0>',
'#\[hr\]#si' => '<hr>',
'#\[email\](.*?)\[/email\]#si' => '<a href="mailto:\\1" class="sm">\\1</a>'
);
$output = preg_replace(array_keys($bbcode), array_values($bbcode), $string);
$output = preg_replace('#\[part\](.+?)\[\/part\]#si', bbpartsearch("$1"), $output);
return $output;
}