0

I've this URL:

https://example.com/[photo-s]/photo.jpg

Sometimes the part between [] changes.

How in PHP, can I replace this part with another thing ?

Example:

preg_replace('photo-[a-z]', 'newphotopath', 'photo-s');
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
F__M
  • 1,518
  • 1
  • 19
  • 34

2 Answers2

0
$url = 'https://example.com/[photo-s]/photo.jpg';
preg_replace('~\[(.*?)\]~', 'something_new', $url);

->

https://example.com/something_new/photo.jpg

If you mean to replace everything between .com/ and the following / regardless of having brackets or not you could use:

preg_replace('~.com\/(.*?)\/~', '.com/something_new/', $url)

->

https://example.com/something_new/photo.jpg
Gab
  • 3,404
  • 1
  • 11
  • 22
0

Code

$target = 'https://example.com/[photo-s]/photo.jpg';
$result = preg_replace('/\[photo-[a-z]+]/', 'somethingElse', $target);

Output

string(43) "https://example.com/somethingElse/photo.jpg"

Working example.

SirPilan
  • 4,649
  • 2
  • 13
  • 26