» PHP Recursive str_replace: replaceTree

3 Tree Manipulation

PHP Recursive functions

Yep, that's a tree alright.In real life I do not consider myself to be a tree-hugger, but as a developer: tree data structures and recursive technology totally get me going ;) Seriously though, they are very powerful ways to solve problems and often lead to elegant & reusable solutions.

In this series I am going to share a couple of functions and ways of approaching recursive problems in PHP.

On twitter

Working with trees

When working with tree data structures you often need to craft them in different ways. PHP offers a lot of functions to change the shape of arrays, but often they only go 1 level deep. Trees can count an almost infinite number of levels. Hence we need recursive replacements for our beloved array & string functions.

replaceTree

replaceTree is the tree version of str_replace. It will recursively replace through an array of strings.

<?php
/**
 * Recursive alternative to str_replace that supports replacing keys as well
 * 
 * @param string  $search
 * @param string  $replace
 * @param array   $array
 * @param boolean $keys_too
 * 
 * @return array
 */
function replaceTree($search="", $replace="", $array=false, $keys_too=false)
{ 
    if (!is_array($array)) {
        // Regular replace
        return str_replace($search, $replace, $array);
    }
    
    $newArr = array();
    foreach ($array as $k=>$v) {
        // Replace keys as well?
        $add_key = $k;
        if ($keys_too) {
            $add_key = str_replace($search, $replace, $k);
        }
        
        // Recurse
        $newArr[$add_key] = replaceTree($search, $replace, $v, $keys_too);
    }
    return $newArr;
}
?>

Stay up to date

You can track my blog rss articles and rss comments. You may also find my rss bookmarks interesting. Or twitter Follow me on Twitter


Like this Article?

Your money is no good here, but
you can boost morale by spreading the word! : )


tags: php, programming, recursion, hierarchy, tree data structure, array, parsing
category: Programming - PHP - Tree Manipulation
read: 7,359 times

Add comment

(required, shown)(required, not shown)for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

 Track replies: rss feed comments feed

Comments

#3. YPI prem on 10 July 2009

Gravatar.com: YPI premThis is really awesome. PHP doesn't allow this as a inbuilt func, but to me its look generic enuf to be included in pHp6

#2. Alex on 12 March 2009

Gravatar.com: AlexAwesome function, solved my problem right away!

#1. prem ypi on 26 February 2009

Gravatar.com: prem ypiThis looks nice piece of code, specially when i have to edit a sentence having specific character sequences.
But would ve been better if recursive replace was part of inbuilt php functions itself.