1

I'm pretty sure this is some stupid mistake from me but i haven't been able to debug where the error in this lies.

I'm trying to change image paths in html file with this regexp. It should work, but preg_replace is just returning null time after time.

preg_replace("(src=){1}([\"']){1}(.*)([\/]+)(.*[\"']{1})", '/my/path'.$5 , $source);

anyone care to lend a hand please?

Nikkeloodeni
  • 93
  • 1
  • 3
  • 7

3 Answers3

6

There's a lot going on here.

  1. /(src=){1}/ is the same as /src=/
  2. .* probably isn't doing what you expect, as it matches a blank string (and is set to be greedy)
  3. You are concatenating $5 to a string, but $5 will not be set in PHP; you probably meant '/my/path$5'

Really though, if you're trying to pull the src attribute out of an HTML (or XML) tag, you should be using the DOM. Refer to this comment.

Community
  • 1
  • 1
Annika Backstrom
  • 13,937
  • 6
  • 46
  • 52
  • I'm supposed to change paths of all images in a html file. So the filename itself should stay the same while only the path should change. I thought this would be nice n' easy with regex. quess not.. – Nikkeloodeni Apr 07 '10 at 12:48
3

You should look at preg_last_error() after you've run into such an error.

More information is available here: http://www.pelagodesign.com/blog/2008/01/25/wtf-preg_replace-returns-null/ or on http://www.php.net/preg_last_error

Yvan
  • 2,539
  • 26
  • 28
1

Your pattern has a lot of unnecessary complications, try this:

preg_replace('#src=[\'"](.*?)[\'"]#", '/my/path$1', $source);

if you know you'll only be seeing double quotes, it's even neater:

preg_replace('#src="(.*?)"#", '/my/path$1', $source);

EDIT

Reading your comments maybe you want this?

preg_replace('#(<img\s*.*src=")#', '$1/my/path/', $source);
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
  • Can't even get this to work. Still returning null. Same effect with preg_grep function. I'm totally lost here. – Nikkeloodeni Apr 07 '10 at 12:50
  • it's closer, but i need to change image paths (like http://www.example.com/image.jpg) to absolute path on my server (like /var/path/image.jpg) for all images in this html document. so that's why i need all filenames from src attribute. – Nikkeloodeni Apr 07 '10 at 13:02
  • oh yeah that worked otherwise ty :) so it's clearly a failure in my regex. – Nikkeloodeni Apr 07 '10 at 13:03