PHP preg_replace weirdness

If you touch your software enough does it become hardware?

Moderator: Forum Moderators

Post Reply
ProfHawking
Zombie
Zombie
Posts: 2101
Joined: February 20th, 2005, 21:31

PHP preg_replace weirdness

Post by ProfHawking »

Any PHP bods got a spare sec? A little weirdness with a regular expression thing is confusing my little brain


Baically, i have a need to search a string for a reference, eg: [brandid:10]
then take that brand ID, 10, into a database and get its proper name.

So, blah blah blah [brandid:10] blah
becomes
blah blah blah <a href="/visit?brandten">brandten</a> blah

So far, so good with a little preg_replace:

$content = preg_replace('/\[brandid:(.*)]/', test1('$1'), $content);

Where the function is:

Code: Select all

function test1($text) {
        return "<a href="/visit/$text">$text</a>";
}
so it is taking the supplied id, giving it to the function and getting the right result.

So, now i need to get it from a database

Code: Select all

function test3($id) {
		$sql = mysql_query ("SELECT name FROM brands WHERE id=$id");
		// return value
		$row = mysql_fetch_array($sql);
		return "<a href="/visit/".$row[name].">".$row[name]."</a>";

}
If i call this new function separately, it works fine. If i call it in the preg_replace as above, it fails miserably, returning blank and gives me no indication of what has gone wrong.

Anyone got any thoughts as to why? Cheers muchly!!

// note: phpbb seems to remove various things from the code, i have escaped things and such
Stoat
Site Admin
Site Admin
Posts: 3291
Joined: October 8th, 2004, 15:48
Location: Sheffield, UK
Contact:

Post by Stoat »

I haven't set up a database to test that but the code works fine for me, supplying $row[name] directly.
I'd return $sql and check it's being formed correctly and that $row is being returned as expected.
And that you're calling test3 :lol:
Stoat
Site Admin
Site Admin
Posts: 3291
Joined: October 8th, 2004, 15:48
Location: Sheffield, UK
Contact:

Post by Stoat »

Ah, got it. The backreference isn't being passed to the function, it's sending "$1" literally.

This works for me.
The e delimiter is like eval(). Hashes used for clarity.

Code: Select all

$content = preg_replace("#\[brandid\:(.*)\]#e", "test3('\\1')",  $content);
ProfHawking
Zombie
Zombie
Posts: 2101
Joined: February 20th, 2005, 21:31

Post by ProfHawking »

Cheers dude!
I couldnt actually get it working with the \e, but it set me on the right course.

In the end i have used

Code: Select all

preg_replace_callback('#\[brandid:(.*)]#', regbrandname, $content[content]);
and

Code: Select all

function regbrandname($id){
	$sql = mysql_query ("SELECT name FROM brands WHERE id=".$id[1]."");
	$row = mysql_fetch_array($sql);
	return '<a href="/visit?'.$row[name].'">'.$row[name].'</a>'; 
}
which seems to do the trick. Whenever you next bashaga/lanage i must owe you a whole crate of beers by now :ahoy:
Post Reply