Re: regexp problem
| From: | Chris Jones | Date: | Mon, 18 Dec 2000 19:50:14 +0000 |
| Subject: | Re: regexp problem | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-30902@lists.php.net to get a copy of this message | ||
Hi
> ereg_replace('([^[:alnum:]]|^)foo([^[:alnum:]]|$)',
> '[\\1]FOO[\\2]', $text) ) . "\n";
>
> Tell us if you found a better code :-)
I did look at doing it in a similar way to what you suggest, but I found a
more readable way of doing it by moving to preg_replace() (although I
can't guarantee it's faster since I'm not familiar with the internals of PHP's
code). The snippet below is how I've got it working. The idea behind the code
is that it grabs the keywords and what they should be substituted with. In
this case, it's designed to the keywords into links. Not a hugely
important feature, but it's rather nice.
<?
$text = "Some text from some other place";
$db = mysql_connect ($sql_host, $sql_user, $sql_pass);
mysql_select_db ($sql_db, $db);
$query = "SELECT sText,sURL FROM ld_subs";
$res = mysql_query ($query, $db);
for ($i = 0; $i < mysql_num_rows ($res); $i++) {
$row = mysql_fetch_row ($res);
$regexp = "/\b" . $row[0] . "\b/";
$result = "<a href=\"" . $row[1] . "\">" . $row[0] .
"</a>";
$text = preg_replace ($regexp, $result, $text);
}
mysql_free_result ($res);
mysql_close ($db);
print ($text);
?>
I'm really not sure why preg_replace() requires the leading and trailing
slash characters to be on the regexp, but then I'm no expert with perl
regexp's.
If anyone can improve on that code, let me know!
--
_____ _ _ _____
| __ | |___ ___| |_ ___| __|_ _ ___ Chris "Ng" Jones
| __ -| | .'| _| '_|___|__ | | | | chris@black-sun.co.uk
|_____|_|__,|___|_,_| |_____|___|_|_| www.black-sun.co.uk
S o f t w a r e