php – How do I remove content between X and Y using preg_replace? – Education Career Blog

What would the regular expression be for removing any content between a quote, and the directory “uploads/”?

Using a regexpression generator, I get this: (?<=\=”)^+?(?=uploads/)

$block_data = preg_replace('/(?<=\=")^+?(?=uploads/)/g','',$block_data);

But seems to be removing everything 🙁


You should escape the “/” in “uploads/” and g isn’t a valid modifier, plus ^ is invalid, I guess you wanted . instead.

Here is your regex :


The test on ideone


The simple solution would be

$block_data = preg_replace('/(?<=").*?(?=uploads\/)/','',$block_data);

Changes made:

  1. Simplified your lookbehind and lookahead assertions
  2. escaped the / in the lookahead
  3. removed the g modifier, which is unnecessary in PHP

This works, so far as I can tell, reducing first"middle/uploads/end" to first"uploads/end".

Leave a Comment