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!
I need to define a string and then eval it later once the $vars have been declared (this will let me define a single "perform search" method in a parent - otherwise I have to duplicate the code in several childs although $link is the only unique bit for each child).
<?php
// RULES:
// $array['key'] creates an error - declare $var = $array['key']; first and use $var
// concatenate string and '$var' elements (enclose $vars within single quotes)
// if vars followed by certain chars (underscore - et al?) write like this: ' . $var . ' and then str_replace later to strip ' . '
// using " instead of ' in $string doesn't seem to work
$string = '(dupe info: ID' . '$tid' . ') <a href="index.php?page=forum_lp_' . ' . $terms_string_GET . ' . '_' . ' . $tid . ' . '_1_1">' . '$board_title' . ' | ' . '$title' . '</A><br />';
// declare vars
$tid = 12;
$terms_string_GET = 'search_terms';
$result['board_title'] = $board_title = 'I am a board title.';
$result['title'] = $title = 'I am a topic title.';
// eval
eval("\$link = "$string";");
$link = str_replace(' . ', '', $link);
?>
The manual doesn't give a lot of help with preparing concatenated strings for eval. And after several hours that's the best I can work out.. but I must be doing something wrong if I need to str_replace ?
Last edited by McGruff on Thu Aug 11, 2005 5:42 am, edited 1 time in total.
In the first example, the string is correct if you just want to define a concatenated string - but it didn't work with eval.
The second string does eval successfully.
(1) $array['key'] has to be replaced with $var (=$array['key'])
(2) if a $var is followed by an underscore, I had to put in some ' . ' and then strip them out later.
I think eval is second only to regex'ing in terms of hair-pulling potential. I'm almost completely bald now.