本篇文章是对PHP正则提取或替换img标记属性进行了详细的分析介绍,需要的朋友参考下
核心代码
<?php /*PHP正则提取图片img标记中的任意属性*/ $str = '<br />PHP正则提取或更改图片img标记中的任意属性'; //1、取整个图片代码 preg_match('/]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$str,$match); echo $match[0]; //2、取width preg_match('//i',$str,$match); echo $match[1]; //3、取height preg_match('//i',$str,$match); echo $match[1];<strong style="color:transparent">来源gaodai#ma#com搞@代~码网</strong> //4、取src preg_match('//i',$str,$match); echo $match[1]; /*PHP正则替换图片img标记中的任意属性*/ //1、将src="/uploads/images/20100516000.jpg-600"替换为src="/uploads/uc/images/20100516000.jpg-600") print preg_replace('/()/i',"\${1}uc/images/\${3}",$str); echo "<hr />"; //2、将src="/uploads/images/20100516000.jpg-600"替换为src="/uploads/uc/images/20100516000.jpg-600",并省去宽和高 print preg_replace('/(/i',"\${1} \${2}uc/images/\${3}>",$str); ?>
PHP获取所有图片地址正则表达式
不带图片的所有图片地址匹配:
preg_match_all(‘/(\s+src\s?\=)\s?[\’|”]([^\’|”]*)/is’, $request->input(‘detail_content’), $match);
带data:image/的:
preg_match_all(‘/(\s+src\s?\=)\s?[\’|”]([^\’|”]*)[data]/is’, $request->input(‘detail_content’), $match);
PHP正则获取一段字符串中所有图片地址
有的时候我们需要获取文章内容或者字符串中所有的图片地址,那么我们首先想到的就是正则匹配,该怎么实现呢,下面就是小编的亲测方法
$str = '<p><br /></p>'; $preg = '//i';//匹配img标签的正则表达式 preg_match_all($preg, $str, $allImg);//这里匹配所有的img echo '<pre class="prettyprint linenums">'; print_r($allImg);
输出结果如下
( [0] => Array ( [0] => [1] => [2] => ) [1] => Array ( [0] => /upload/20180621/1529561322214.png-600 [1] => /Home/images/404.jpg-600 [2] => /upload/20180621/1529561322214.png-600 ) )
以上就是解析PHP正则提取或替换img标记属性的详细内容,更多请关注gaodaima搞代码网其它相关文章!