Problem with PHP preg_replace

This is the next question I posted here (thanks mario )

So, I have a preg_replace statement to replace the url string with sometext, paste the value from the query string (using $_GET["size"]) and paste the value from the associative array (using the $fruitArray["$1"]backlink.)

Enter the URL string:

http://mysite.com/script.php?fruit=apple

The output line should be:

http://mysite.com/small/sometext/green/

I have PHP:

$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);

This code displays the following line:

 http://mysite.com/small/sometext//

The code seems to miss the value in $fruitArray["$1"].

What am I missing?

Thank!

+3
source share
4 answers

Well, strange.

Your code works fine for me (see below code that I used for local testing).

2 :

  • | , .
  • , , . s. http://www#mysite%com/script*php?fruit=apple.

script:

$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('@http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)@e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;

:

Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/

, , , $fruitArray .


, , , , , e evil(), PHP;-) , .

$result = preg_replace_callback('@http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)@', function($matches) {
        global $fruitArray;
        return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
+1

, , , preg php

preg_replace(
    '|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
    , '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
    , $result
);
+1

Looks like you forgot to avoid ?. It must be /script.php\?, with \?, to escape properly, as in the answer you linked.

0
source

$ fruitArray ["\ $ 1"] instead of $ fruitArray ["$ 1"]

0
source

All Articles