2014-02-12 16 views
0

您好,我希望有人能帮助我解决这个preg_replace问题,我有preg_replace函数来捕捉图像标签内

我有以下preg_replace("/(\/[^\/]*.jpg)/", ".jpg", $input_lines);

的想法是,以取代在我的WordPress网站图像他们原来的名字......文件已经存在于非缓存文件夹,所以我不用担心那部分......

<img src="http://url.com/wp-content/uploads/cache/2014/02/flag/278439615.jpg"> 

我有一个替换照顾的cache的网址,所以我我留下了网址是这样的:

<img src="http://url.com/wp-content/uploads/2014/02/flag/278439615.jpg"> 

现在,下一步将剥离从URL的数量可以是字母或数字number.jpg

中的所有URL的常量是/最后一次出现和其preg_replace("/(\/[^\/]*.jpg)/", ".jpg", $input_lines);需要照顾

.jpg问题不过是preg_replace函数需要去寻找标签图像标签,而不是取代任何不在图像标签中的代码...

我该如何添加到正则表达式(preg_replace)中以仅查看替换的图像标签内部?

理想的最终结果将是类似如下的URL:

<img src="http://url.com/wp-content/uploads/2014/02/flag.jpg"> 

正则表达式(preg_replace函数)也需要更换匹配的所有出现(有可能是页面上的多个图像)。

您的帮助将不胜感激!

回答

0

您可以使用此替代:

$pattern = <<<'EOD' 
~ 
<img \s 
(?> [^>s]++ | \Bs | s(?!rc\s*=))* # possible content before the src attribute 
src \s* = \s* ["']? [^"\'\s>]+? # start of the src attribute (until /cache/) 
\K         # reset all from match result 
/cache(?=/) 
([^\s"'>]*?)      # capture the path before the filename 
/[^\s/]+ (?=\.jpg [>"'\s])   # the filename followed by the .jpg extension 
~ix 
EOD; 
$result = preg_replace($pattern, '$1', $input_lines);