Jump to content

preg_replace loop? (aka, capture each individual replacement)


techiefreak05

Recommended Posts

Hello all, it's been years since I've been here, but I've ran into a small issue. I'm making a script where users can "tag" other users in their posts, (ex, "Hello, @staff") If they post that,my code captures the tag, and replaces it with the link to that users website... but is there anyway I can capture every single person they tag, and run a query for every person, and send that person a notification when someone tags them?

 

I have this right now,

<?php
$text = preg_replace("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='/user/$1' target='_blank'>$0</a>", $text);
?>

Thanks in advance!

Use preg_replace_callback, and in the callback you can do whatever you need to do to each match.

 

It might look something like this:

 

$text = preg_replace_callback(
"/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/",
create_function(
	'$matches',
	/* do whatever you need to do */ 'return "<a href=\'/user/{$matches[1]}\' target=\'_blank\'>{$matches[0]}</a>";'
),
$text
);

I was thinking you could do something like this, to avoid having to do multiple preg_*() calls (but I wasn't sure which would be faster, so I did a benchmarking test):

 

preg_match_all("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", $text, $matches);
for($i = 0, $n = sizeof($matches[0]);$i < $n;++$i) {
$text = str_replace($matches[0][$i], "<a href='/user/{$matches[1][$i]}' target='_blank'>{$matches[0][$i]}</a>", $text);
}

// Use $matches[1] for the usernames to notify

 

Ran 1000 times took an average of about 0.15 Seconds

 

This turned out to actually be faster:

 

$text = preg_replace("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", "<a href='/user/$1' target='_blank'>$0</a>", $text);

preg_match_all("/(?<=\A|[^A-Za-z0-9_])@([A-Za-z0-9_]+)(?=\Z|[^A-Za-z0-9_])/", $text, $matches);

// Use $matches[1] for the usernames to notify

 

Ran 1000 times took an average of about 0.10 Seconds

 

Just because I was curious I ran my original solution through too, and that took an average of about 0.085 seconds / 1000 loops.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.