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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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);

3 Comments

Can't even get this to work. Still returning null. Same effect with preg_grep function. I'm totally lost here.
it's closer, but i need to change image paths (like 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.
oh yeah that worked otherwise ty :) so it's clearly a failure in my regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.