GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

preg_replace() digits to an array item

I've got this array:

<?php

    $menu = array(
        9 => 'pages/contact/',
        10 => 'pages/calender/jan/'
        //...
    );

?>

And I've got a string that looks like this:

$string = "This is a text with a <a href="###9###">link</a> inside it.";

I want to replace ###9### with pages/contact/.

I've got this:

$string = preg_replace("/###[0-9]+###/", "???", $string);

But I can't use $menu[\\\1]. Any help is appreciated.

Upvotes: 1

Views: 49

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89574

There is a solution with preg_replace_callback but you can build an array where searched strings are associated to their replacement strings and then use strtr:

$menu = array(
9 => 'pages/contact/',
10 => 'pages/calender/jan/'
.... );

$keys = array_map(function ($i) { return "###$i###"; }, array_keys($menu));
$rep = array_combine($keys, $menu);

$result = strtr($string, $rep);

Upvotes: 2

Rizier123
Rizier123

Reputation: 59701

For this you need preg_replace_callback(), where you can apply a callback function fore each match, e.g.

$string = preg_replace_callback("/###(\d+)###/", function($m)use($menu){
    if(isset($menu[$m[1]]))
        return $menu[$m[1]];
    return "default";
}, $string);

Upvotes: 1

Related Questions