1

Hye! This is my first question here, so sorry in advance if I don't get it right.

I want to insert pictures from a gallery in a description text by using #pic1# (#pic2# and so on) in the text and replace it with

Here is the code:

<?
$myString =$art[0][page_text];
$pics=mysql_query_assoc("select * from pages_galerie where id_page='".$id_page."'");
$count= count($pics);
for ($i=0; $i < $count; $i++) {
$search='#pic'.$i+1.'#';
$img=$pics[$i][pic];
$newString = str_replace($search, "<img src=".SITE_URL."pics/medium/".$img.">", $myString);
}
?>

It doesn't work! What do I do wrong?

3
  • Can you give an example of what's in $pics? (Edit the question and copy/paste some of it in there) Commented Sep 23, 2012 at 18:11
  • If $id_page stems from a GET/POST variable, that's asking for a SQL injection. Also, you forgot quotes in the array key on this line $img=$pics[$i][pic]; it should be $img=$pics[$i]['pic']; Commented Sep 23, 2012 at 18:12
  • just a small off-topic point, but the short-form <? tag is not recommended. It is better to always use the long form <?php. (many PHP servers have the short tags disabled) Commented Sep 23, 2012 at 18:31

1 Answer 1

1

Try this http://codepad.org/2NBlkDN9

<?
$myString =$art[0][page_text];
$myString = '#pic1# #pic2#';
//$pics=mysql_query_assoc("select * from pages_galerie where id_page='".$id_page."'");
$pics = array(
   array('pic' => 'TEST1'),
   array('pic' => 'TEST2'),
   array('pic' => 'TEST3'),
);
$count= count($pics);

$newString = $myString;
for ($i=0; $i < $count; $i++) {
$search='#pic'.($i+1).'#';
$img=$pics[$i][pic];

$newString = str_replace($search, "<img src=".SITE_URL."pics/medium/".$img.">", $newString);
}
echo $newString;
?>

You were performing the replacement in $myString and storing it in $newString everytime. Hence only the last replacement had any effect on the final output. I have initialzed $newString with $myString and performed the replacement in $newString.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.