tags:

views:

50

answers:

2

So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :

$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
    ${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}

// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
    $thisWord = $story[$i];
    if ($thisWord[0] == '*')
     $story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);

echo $story;
+1  A: 

Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:

$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
    $storyString .= $story[i] . ' ';
}

echo $storyString;

echo can't print an array, but you can echo strings to your heart's content.

Frank DeRosa
$story is a text and not an array. but i will try to look at the code and see if it can help.
c2009l123
Forget it, it's still going to be hosed. You're trying to parse the string and replace the instances of * with the words that were passed in, but your code is doing... something else. I think I could write code to do what you're wanting, but I can't explain what you're doing wrong and how to fix it, especially since I can't really put together a real simulation of what's happening here. Instead, I suggest you use echo to print some variable values at different times to see what values PHP has so that you're clear on what data is what, at what time.
Frank DeRosa
@c2009l123: In the second `for` loop, you're treating `$story` as an array of words.
outis
You could always make an array of words or word like structures... `$words = explode(' ', $story);`That would deliver everything in the `$story` variable separated by spaces.
Frank DeRosa
A: 

You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.

preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,

function sequence($arr) {
    return function() {
      static $i=0
      $val = $arr[$i++];
      $i %= count($arr);
      return $val;
    }
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");

will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.

outis