Page 1 of 1

preg_replace <a

Posted: Tue Mar 25, 2003 4:47 pm
by andywhitt
I'm trying to find every occurence of

<A HREF = "(.*)">(.*)</A>

and replace it with

[url = "1"]2[/url]

and then change it back again, i have started on the way to converting from <a to [url] this is what i have so far:

Code: Select all

<?
set_time_limit(0);
require("db.php");

$result = mysql_query("select * from table") or die(mysql_error());
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
	$str = preg_replace("<a href="(.*?)">(.*?)</a>", "\[URL\]1\[\/URL\]", $line["txt"]);
	$str = preg_replace("<A HREF="(.*?)">(.*?)</A>", "\[URL\]1\[\/URL\]", $line["txt"]);
	$str = preg_replace("<A href="(.*?)">(.*?)</a>", "\[URL\]1\[\/URL\]", $line["txt"]);
	if($str != $line["Body"])
		$count++;
	$ID = $line["ID"];
	$update = mysql_query("update posts set Body = '$str' where ID = $ID") or die(mysql_error());
}
print "Sucessfull: " .$count ."texts were affected";
?>
With this been my first post here, hi all, if you want to check out my forums that i have written in PHP then please do, drop by and say hi. Link in Sig.

any help will be appreciated, thanks :)

Posted: Wed Mar 26, 2003 6:53 am
by volka
PCRE-patterns have to be encapsulated by delimeter-characters that do not appear (unescaped) within the pattern !<pattern>!<option>
e.g. $pattern = 'a(.*)a'; using a as delimeter (although /, !, _ are more common ;) )
There are some options you can pass to PCRE after the second delimeter. One of them is i to make the pattern case-insensitive. e.g. $pattern ='!<A HREF!i' will match <a href=, <a HREF=, <A HrEf=, ...
<A HREF = "(.*)">(.*)</A>
To avoid unexpected results you should (if possible) exclude unwanted charaters. Try

Code: Select all

<html><body><?php
$line = '<a href="test1.link">test1</a><A hReF="test2.link">test2</a>';
$pattern = '!<A HREF="(.*)">(.*)</A>!i';
$str = preg_replace($pattern, ' test ', $line);
echo htmlentities($str);
?></body></html>
and then

Code: Select all

<html><body><?php
$line = '<a href="test1.link">test1</a><A hReF="test2.link">test2</a>';
$pattern = '!<A HREF="([^"]*)">([^<]*)</A>!i';
$str = preg_replace($pattern, ' test ', $line);
echo htmlentities($str);
?></body></html>
The replacement-parameter of preg_replace is not a regex so there is no need to escape [, ]
fetched substrings can be accessed via $1, $2, ...

Code: Select all

<html><body><?php
$line = 'abcde <a href="test1.link">test1</a>123456abcde <A hReF="test2.link">test2</a>';
$pattern = '!<A HREF="([^"]*)">([^<]*)</A>!i';
$str = preg_replace($pattern, '[url="$1"]$2[/url]', $line);
echo htmlentities($line);
echo '<br />';
echo htmlentities($str);
?></body></html>
online manual:
http://www.php.net/manual/en/ref.pcre.php
http://www.php.net/manual/en/language.types.string.php