Preg_replace () Only the specific part of the line

I always have problems with regex, I basically have a url like this:

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

I need preg_replace () to replace something_here an empty string and leave everything else in tact.

I tried the following and replace the wrong parts:

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

The result is only the part that I want to replace, instead of replacing it!

+4
source share
3 answers

The following code is based on the description you provided:

 $url = 'http://somedomain.com/something_here/bla/bla/bla/bla.jpg'; $output = preg_replace('#^(https?://[^/]+/)[^/]+/(.*)$#', '$1$2', $url); echo $output; // http://somedomain.com/bla/bla/bla/bla.jpg 

Explanation:

  • ^ : start of line match
  • ( : start group matching 1
    • https?:// : compliance with http or https protocol
    • [^/]+ : match anything other than / one or more times
    • / : match /
  • ) : final match group 1
  • [^/]+ : match anything other than / one or more times - / : match /
  • ( : start group 2 matching
    • .* : match any zero or more (greedy)
  • ) : final match group 2
  • $ : line ending match
+6
source

You can do it:

 $image[0] = preg_replace('!^(http://[^/]*)/[^/]*!', '$1', $image[0]); 

Or you can simply split the string into separate components:

 $parts = explode('/', $image[0]); unset($parts[3]); $image[0] = implode('/', $parts); 
+2
source

You can do this with a simple line:

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

Or if you want to use regex:

 $image[0] = preg_replace('~(http://.*?)/wp-content/uploads/(.*)~', '$1/$2', $image[0]); 
+1
source

Source: https://habr.com/ru/post/1493383/


All Articles