Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace problem

Tags:

regex

url

php

This is a follow-up question to the one I posted here (thanks to mario)

Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)

Input url string would be:

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

Output string should be:

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

The PHP I have is as follows:

$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 codes outputs the following string:

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

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

What am I missing?

Thanks!

like image 464
Matt Avatar asked Jul 12 '26 21:07

Matt


1 Answers

Well, weird thing.

Your code work's perfectly fine for me (see below code that I used for testing locally).

I did however fix 2 things with your regex:

  1. Don't use | as a delimiter, it has meaning in regex.
  2. Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.

Test 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;

Output:

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

The only thing this leads me to think is that $fruitArray is not setup correctly for you.


By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.

$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);
like image 70
Rudi Visser Avatar answered Jul 14 '26 13:07

Rudi Visser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!