preg-replace - syntax/insertion of code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mesz
Forum Contributor
Posts: 216
Joined: Fri May 23, 2003 8:11 am
Location: M/cr

preg-replace - syntax/insertion of code

Post 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
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post 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);
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
User avatar
mesz
Forum Contributor
Posts: 216
Joined: Fri May 23, 2003 8:11 am
Location: M/cr

Post 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.
User avatar
mesz
Forum Contributor
Posts: 216
Joined: Fri May 23, 2003 8:11 am
Location: M/cr

Post 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]);
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post 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)
Post Reply