PHP中正则表达式操作函数
高级使用:
输出结果:
preg_grep 只匹配,不替换。
preg_match_all("/\<img.*src=\"https:\/\/mmbiz\.qpic\.cn\/mmbiz_.*\".*\>/iesU", $message, $match); foreach ($match[0] as $i => $item) { $img_url = preg_replace("/\<img.*src=\"(.*?)\".*\>/", "\\1", $item); $img_type = preg_replace("/\<img.*data-type=\"(.*)\".*\>/", "\\1", $item); if(!in_array($img_type, array('gif', 'png', 'jpg', 'jpeg'))) { switch (true) { case strstr($img_url, 'gif'): $img_type = 'gif'; break; case strstr($img_url, 'png'): $img_type = 'png'; break; case (strstr($img_url, 'jpg') || strstr($img_url, 'jpeg')): $img_type = 'jpg'; break; default: $img_type = 'gif'; } } $img_filename = md5($item).'.'.$img_type; $img_file = download_image_url($img_url, $img_filename); $img_file = str_replace(TEMP_PATH,"{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/runtime/",$img_file); $message = str_replace($item, "<img src='{$img_file}' style='max-width:100%;'>", $message); } preg_match_all("/background-image:\s*url\(.*https:\/\/mmbiz\.qpic\.cn\/mmbiz_.*\)/isU", $message, $match1); foreach ($match1[0] as $item) { $img_url = htmlspecialchars_decode($item); $img_url = preg_replace("/background-image:\s*url\(\"(.*)\"\)/", "\\1", $img_url); $img_type = preg_replace("/background-image:\s*url\(\".*?wx_fmt=(.*)\"\)/", "\\1", $item); if(!in_array($img_type, array('gif', 'png', 'jpg', 'jpeg'))) { switch (true) { case strstr($img_url, 'gif'): $img_type = 'gif'; break; case strstr($img_url, 'png'): $img_type = 'png'; break; case (strstr($img_url, 'jpg') || strstr($img_url, 'jpeg')): $img_type = 'jpg'; break; default: $img_type = 'gif'; } } $img_filename = md5($item).'.'.$img_type; $img_file = download_image_url($img_url, $img_filename); $img_file = str_replace(TEMP_PATH,"{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}/runtime/",$img_file); $message = str_replace($item, "background-image: url('{$img_file}')", $message); } preg_match_all("/\<img.*src=\"https:\/\/qimg\.haodian\.cn\/.*\".*\>/iesU", $message, $match2); foreach ($match2[0] as $item) { $img_url = preg_replace("/\<img.*(src=\".*?\").*\>/", "\\1", $item); $new_item = str_replace($img_url,$img_url.' style="max-width:100%;" ',$item); $message = str_replace($item, $new_item, $message); } if ($match[0] || $match1[0] || $match2[0]){ $ifupload = 1; } //var_dump($message); //$message = htmlspecialchars($message); $search_arr = array("\t","\n","\r"); $replace_arr = array("","",""); $message = str_replace($search_arr,$replace_arr,$message);