kilrizzy
kilrizzy

Reputation: 2943

How do I remove content between X and Y using preg_replace?

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 :(

Upvotes: 1

Views: 561

Answers (2)

lonesomeday
lonesomeday

Reputation: 237847

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".

Upvotes: 2

Colin Hebert
Colin Hebert

Reputation: 93157

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 :

/(?<=\=").+?(?=uploads\/)/

The test on ideone

Upvotes: 3

Related Questions