Question: I got this HTML:

```
<p>
  <img src="../test/test2/test3/image.png">
  <img src="../test/test2/test3/test4/image2.png">
</p>

```

The `../test` is always there, oher directories are optional.

Now, I want it to look like is this:

```
<p>
  <img src="image.png">
  <img src="image2.png">
</p>

```

I've been thinking about a `preg_match` to scan for urls and then replace those in a loop, but a single preg\_replace would be neater. 

I tried this regex, but I can't figure out how to make it greedy enough to keep the filename without catching other HTML. A non-greedy regex will just stop at the first subfolder.

```
preg_replace('@\.\./test/.*/@', '', $content);

```

EDIT: for clarity, this HTML is read from a database and needs to be processed. This is an example, real HTML may contain far more links and content, so I can't do manual edits. Also, I'm familiar with the basename() function. I'm looking for a **pure regex solution** here.

Answer: 
**Regex:**

```
(<img src=")(.*\/test.*\/)(.*)$

```

**Replacement string:**

```
\1\3

```

[DEMO](http://regex101.com/r/aU1nR4/12)

PHP code would be,

```
<?php
$url = <<< 'EOT'
<p>
  <img src="../test/test2/test3/image.png">
  <img src="../test/test2/test3/test4/image2.png">
</p>
EOT;
$regex = '~(?m)(<img src=")(.*\/test.*\/)(.*)$~';
$replacement = "$1$3";
echo preg_replace($regex, $replacement, $url);
?>

```

**Output:**

```
<p>
  <img src="image.png">
  <img src="image2.png">
</p>

```
This pattern should work with your example in addition to possibly having other tags in front or behind it.

```
$pat = '@.*(<i.+c=")(.*\/)(.*">).*@';
$rep = "  " . '$1$3';

echo preg_replace($pat, $rep, $str);

```