1

My PHP code

$avatarFileName = './public/uploads/avatar\php17C_552334c997e50.png';
preg_replace('/^.\/public\/uploads\/avatar(\\|\/)/', "", $avatarFleName);
print_r($avatarFileName)

Above php code return string:

./public/uploads/avatar\php17C_552334c997e50.png

This is not correct string I want to have. The string I want is

php17C_552334c997e50.png

I tested on site http://www.phpliveregex.com/ and it returns the correct string php17C_552334c997e50.png but not on my php application.

I am using PHP 5.5, anyone give me ideas ?

stema
  • 90,351
  • 20
  • 107
  • 135
Phu Do
  • 11
  • 1

2 Answers2

1
$result=preg_replace('/^.\\/public\\/uploads\\/avatar(\\\\|\\/)/', "", $avatarFleName);

Your regex is working fine.Just assign the return value to a variable and then access it.replace here is not in place.See demo.

https://regex101.com/r/sJ9gM7/108

vks
  • 67,027
  • 10
  • 91
  • 124
0

In PHP you don't delimit your regex with the two / like /regexhere/ because it is already in a string delimiter (' in your case). So you can just do this:

$avatarFileName = './public/uploads/avatar\php17C_552334c997e50.png';
preg_replace('^.\/public\/uploads\/avatar(\\|\/)', "", $avatarFleName);
print_r($avatarFileName)

In most languages it's one of the two, either you have a string that starts and ends with ' or ", or you have a regex literal where you start and end with /. It's never both.

asontu
  • 4,548
  • 1
  • 21
  • 29