Page 1 of 1

preg-replace - syntax/insertion of code

Posted: Thu Jul 17, 2003 8:16 am
by mesz
Tryin' to learn BBcode.
Using preg-replace.
I think my syntax of inserting the preg instruction is at fault

Code: Select all

<?PHP
$data = file('news.dat);
$data = array_reverse($data);
foreach($data as $element) {
preg_replace("/\[img\](.+?)\[\/img\]/", "<img src=$1>", $pieces[2]); 
    $element = trim($element);
    $pieces = explode("|", $element);
echo $pieces[2] . "<BR>" . "<b>Posted by " . $pieces[1] . " on " . $pieces[0] . 
"</b> <BR><BR>". $1.;
}
?>
Error:Parse error: parse error, unexpected $ in /home/.sites/14/site467/web/pstore/add.php on line 13

Posted: Thu Jul 17, 2003 8:23 am
by Stoker
remember to escape backslashes so they become literals, and it is \1 and not $1 to reuse a collected group, and finally you need to assign the result to something (back to itself probably)..

$result = preg_replace('/\\[img\\](.+?)\\[\\/img\\]/', '<img src="\\1">', $source);

Posted: Thu Jul 17, 2003 8:32 am
by twigletmac
Could have been a typo when you posted but you're missing a single quote on this line:

Code: Select all

$data = file('news.dat);
Mac

Posted: Thu Jul 17, 2003 9:09 am
by mesz
:mrgreen: I did this following your advice:

Code: Select all

<?PHP
$data = file('news.dat');
$data = array_reverse($data);
foreach($data as $element) {
$result = preg_replace('/\\[img\\](.+?)\\[\\/img\\]/', '<img src="\\1">', $pieces[2]);
    $element = trim($element);
    $pieces = explode("|", $element);
echo $pieces[2] .
 "<BR>" .
 "<b>Posted by " . 
$pieces[1] .
 " on " . 
$pieces[0] . 
"</b> <BR><BR>". 
$result ;
}
?>
and the image posts.
Cheers a mundo my php friends.

Posted: Thu Jul 17, 2003 9:40 am
by mesz
to add bold or url would it be simly a case of this?

Code: Select all

$result_1 = preg_replace('/\\[b\\](.+?)\\[\\/b\\]/', '<b="\\2">', $pieces[2]);

Posted: Thu Jul 17, 2003 10:15 am
by Stoker
\1 not \2 as you have no more than 1 group.. you can also assign to the same source as you are reading from, and a thirs option is to use to arrays with all your search/replace strings in it (see the manual)