Alex Rivera | Logout

preg_replace() Only Specific Part Of String

Asked 2013-07-25T08:13:03.527
8

I always have trouble with regex, I basically have a url, for example:

http://somedomain.com/something_here/bla/bla/bla/bla.jpg

What I need is a preg_replace() to replace the something_here with an empty string, and leave everything else in tact.

I have tried the following and it replaces the wrong parts:

$image[0] = preg_replace('/http:\/\/(.*)\/(.*)\/wp-content\/uploads\/(.*)/','$2' . '',$image[0]);

This ends up leaving only the part I want to replace, rather than actually replacing it!

Edit
Report

1 Answer

1

You could do this with a simple string replace:

$image[0] = str_replace('/wp-content/uploads/', '/', $image[0]);

Or if you want to use a regular expression:

$image[0] = preg_replace('~(http://.*?)/wp-content/uploads/(.*)~', '$1/$2', $image[0]);
answered 2013-07-25T08:21:27.397

Your Answer