I've been having trouble with a piece of code

<?php

$test = "this is just \"a test\"";

echo "\n$test\n\n";

$tags = explode(' ', preg_replace('/"([^"]+)"/e',
"preg_replace('/\s+/','%20','\\1')", $test));

for($i = 0,$c = count($tags); $i < $c; $i++) {
        if(preg_match('/%20/', $tags[$i])) {
                echo "yes ";
        } else {
                echo "no ";
        }
        preg_replace('/%20/', ' ', $tags[$i]);
}

echo "\n\n";
print_r($tags);

?>

$tags is an array containing ('this','is','just','a%20test'). In the for loop i'm going through each element and trying to change back any instances of %20 to a space but it's not working. I've tried ereg and str replace but I get the same result. Using preg_match with the /%20/ pattern returns true though.

Here's the output:

this is just "a test"

no no no yes

Array
(
    [0] => this
    [1] => is
    [2] => just
    [3] => a%20test
)

Any ideas? Thanks.

Could you explain what you're trying to do?

If you want to use a function all for the replacements, you need to use preg_replace_callback().

Programs actually execute the innermost function first, instead of the outtermost. They just execute each line from top to bottom.

ie:

$tags = explode(' ', preg_replace('/"([^"]+)"/e', preg_replace('/\s+/','%20','\\1'), $test));

is the same as:

$replace = preg_replace('/\s+/','%20','\\1');
$tags = explode(' ', preg_replace('/"([^"]+)"/e', $replace, $test));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.