Can you do this with PHP?

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
Take this for example:

PHP:
$query = 'SELECT field1, field2 FROM thisTable ORDER BY dateline LIMIT 5';

$resultSet = '<li><a href="$1">$2</a></li>';

I will want to replace whatever is in $1 and $2 with variables retrived from the query, such as
PHP:
while(GETeachRESULT)
{
// <li><a href="$1">$2</a></li>
// replace $1 with field1 result
// replace $2 with field2 result

// Echo result: <li><a href="3">This is a link</a></li>
}

So to cut it short, how can I replace $1, $2 with certain variables?
If the result set contains $3 then replace this with the field3 in a query. etc.

Or is there a better way to do it?

Thx
 
Last edited:
There are a few ways, this is one of them..

Code:
        $query = 'SELECT field1, field2 FROM thisTable ORDER BY dateline LIMIT 5';
        $result = mysql_query($query);
        $items = array();
        while ($row = mysql_fetch_assoc($result)) {
            $items[] = sprintf('<li><a href="%s">%s</a></li>', $row['field1'], $row['field2']);
        }
        //do something with $items array;

can also just concat the sections of the lines.
 
the sprintf function above is hard coded to take 2 variables, but if it had 3,4...N variables?

Is there not a way to use preg_replace?

replace $1, $2, ... $N in the resultSet with $array[$1] ?
 
Last edited:
not without hardcoding the back references, no. And you would only have up to 10 back references.

Try something like:
Code:
function ArraySprintF ($array, $format)
{
    $i = 0;
    foreach ($array as $item) {
        $format = str_replace(':' . $i++, $item, $format);
    }
    
    return $format;
}

echo ArraySprintF (array('a','b','c'), 'string: :0 :1 :2');

outputs:
string: a b c

for associative references..

Code:
function ArraySprintF ($array, $format)
{
    foreach (array_keys($array) as $key) {
        $format = str_replace(':' . $key, $array[$key], $format);
    }
    
    return $format;
}

echo ArraySprintF (array('one' => 'a', 'two' => 'b', 'three' => 'c'), 'string: :one :two :three');
 
Last edited:
Parsing variables for values.

The first is using numerical values, the latter associative values (you could use the latter to do either, but meh.)

in the format string, you enter a placeholder for a value by denoting it with a colon. The function will replace that placeholder, with the value from the array with the matching key.
 
Back
Top Bottom