note 87383 added to function.str-replace

From: Date: Tue, 02 Dec 2008 22:55:48 +0000
Subject: note 87383 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-147569@lists.php.net to get a copy of this message
Replacement for str_replace in which a multiarray of numerically keyed data can be properly evaluated with the given template without having a search for 11 be mistaken for two 1's next to each other <?php function data_template($input, $template) { if ($template) { // template string if ($split = str_split($template)) { // each char as array member foreach ($split as $char) { // each character if (is_numeric($char)) { // test for digit if ($s != 1) { // new digit sequence $i++; $s = 1; } $digits[$i] .= $char; // store digit } else { // not a digit if ($s != 2) { // new non-digit sequence $i++; $s = 2; } $strings[$i] .= $char; // store string } } if ($i && $input && is_array($input)) { // input data foreach ($input as $sub) { // each subarray if (is_array($sub)) { $out = ''; // reset output for ($j = 0; $j <= $i; $j++) { // each number/string member if ($number = $digits[$j]) { // number $out .= $sub[$number]; // add value from subarray to output } else { // string $out .= $strings[$j]; // add to output } } $a[] = $out; } } return $a; } // input } // split } // template } $input = array(array(1=>'yellow', 2=>'banana', 11=>'fruit'), array(1=>'green', 2=>'spinach', 11=>'vegetable'), array(1=>'pink', 2=>'salmon', 11=>'fish')); print_r (data_template($input, '2: a 1, healthy 11')); Array ( [0] => banana: a yellow, healthy fruit [1] => spinach: a green, healthy vegetable [2] => salmon: a pink, healthy fish ) // str_replace would have wanted to output 'banana: a yellow, healthy yellowyellow ?> Not sure if this will help anyone but I wrote it for my application and thought I would share just in case ---- Server IP: 69.147.83.197 Probable Submitter: 76.245.125.170 ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- https://master.php.net/note/edit/87383 Del: integrated -- https://master.php.net/note/delete/87383/integrated Del: useless -- https://master.php.net/note/delete/87383/useless Del: bad code -- https://master.php.net/note/delete/87383/bad+code Del: spam -- https://master.php.net/note/delete/87383/spam Del: non-english -- https://master.php.net/note/delete/87383/non-english Del: in docs -- https://master.php.net/note/delete/87383/in+docs Del: other reasons-- https://master.php.net/note/delete/87383 Reject -- https://master.php.net/note/reject/87383 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#147569) next »