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);
开发者_JAVA百科
anyone care to lend a hand please?
There's a lot going on here.
/(src=){1}/
is the same as/src=/
.*
probably isn't doing what you expect, as it matches a blank string (and is set to be greedy)- 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.
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
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);
精彩评论