Nikkeloodeni
Nikkeloodeni

Reputation: 93

php preg_replace returning null

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?

Upvotes: 1

Views: 3858

Answers (3)

Yvan
Yvan

Reputation: 2699

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

Upvotes: 3

Matteo Riva
Matteo Riva

Reputation: 25060

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

Upvotes: 1

user7675
user7675

Reputation:

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.

Upvotes: 6

Related Questions