在PHP中,我试图实现更改字符串:
<img class="alignnone size-medium wp-image-18" src="http://localhost/wp-content/uploads/2015/02/300x149-jquerymobile.jpg" alt="jquerymobile" width="300" height="149">
到此:
<img class="alignnone size-medium wp-image-18" src="" data-path="http://localhost/wp-content/uploads/2015/02/" data-img="300x149-jquerymobile.jpg" alt="jquerymobile" width="300" height="149">
我想使用
preg_replace('/src="(what-is-a-path-regex)(.*)"/', 'src="" data-path="$1" data-img="$2"', '<img class="alignnone size-medium wp-image-18" src="http://localhost/wp-content/uploads/2015/02/300x149-jquerymobile.jpg" alt="jquerymobile" width="300" height="149">')
用什么正则表达式来代替"wat-is-a-path-regex"?
这应该有效:(https?:'/'/.+'/)(.+)
。此处提供了一个示例。
也就是说,应该看看是否可以将这种方法与DOM解析相结合,以便首先提取所需的属性。
您可以尝试以下方法,
preg_replace('~src="(.*?'/)([^/"]*)"~', 'src="" data-path="'1" data-img="'2"', '<img class="alignnone size-medium wp-image-18" src="http://localhost/wp-content/uploads/2015/02/300x149-jquerymobile.jpg" alt="jquerymobile" width="300" height="149">');
演示
[^/"]*
否定与任何字符匹配但不与"
或/
匹配的字符类零次或多次。