preg_replace and array values

I need to convert every number inside the curly brackets ('{}') to a hyperlink. The thing is, the string can contain multiple patterns.

$text = 'the possible answers are {1}, {5}, and {26}';
preg_match_all( '#{([0-9]+)}#', $text, $matches );

The output array is like this

Array ( 
[0] => Array ( [0] => {1} [1] => {5} [2] => {26} ) 
[1] => Array ( [0] => 1 [1] => 5 [2] => 26 ) 
)

Here is my current code.

$number=0;
return preg_replace('#{([0-9]+)}#','<a href="#$1">>>'.$matches[1][$number].'</a>',$text);
$number++;

But output is like

The possible answers are
<a href="#1">1</a>, <a href="#5">1</a>, and <a href="#26">1</a>

Only '1' ($matches[1][0]) is being fetched.

How do I fix this?

Answers


what is the problem with this?

return preg_replace('#{([0-9]+)}#','<a href="#$1">$1</a>', $text);

output this:

<a href="#1">1</a>, <a href="#5">5</a>, and <a href="#26">26</a>

if you need to do some math, calculation, lookup...etc for the urls, you can use preg_replace_callback. you just specify a callback function as the replace value, the function gets passed each match one at a time as it is called and the return value from the function is what is the replacement value.

<?php
$text = 'the possible answers are {1}, {5}, and {26}';

$text = preg_replace_callback('#\{([0-9]+)\}#',
    function($matches){
        //do some calculations
        $num = $matches[1] * 5;
        return "<a href='#{$matches[1]}'>{$num}</a>";
    }, $text);
var_dump($text);
?>

http://codepad.viper-7.com/zM7dwm


$text = 'the possible answers are {1}, {5}, and {26}';
$text = preg_replace('/\{(\d+)\}/i', '<a href="#\\1">\\1</a>', $text);
var_dump($text);

string(89) "the possible answers are <a href="#1">1</a>, <a href="#5">5</a>, and <a href="#26">26</a>"

Edit (answer with arrays):

$text = 'the possible answers are {1}, {5}, and {26}';
if (($c = preg_match_all('/\{(\d+)\}/i', $text, $matches)) > 0)
{
    for ($i = 0; $i < $c; $i++)
    {
        // calculate here ... and assign to $link
        $text = str_replace($matches[0][$i], '<a href="'.$link.'"'>'.$matches[1][$i].'</a>', $text);
    }
}

Need Your Help

Break out of double while loops?

python python-2.7 login while-loop

Hello i have this login that i am trying to make and when i get to the command screen if i want to exit out of the program i type "exit", but the problem is i have it in a double while loop and don't

Preventing a NetLogo turtle from hitting a wall

netlogo

I'm trying to do something really simple, but for some reason I just can't get it to work.