国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > CMS > Wordpress > 正文

wordpress中preg_match正則提取和替換字符串

2024-09-07 00:50:29
字體:
來源:轉載
供稿:網友

在wordpress顯示文章的時候,如果文章形式是圖片的文章,需要把里面的圖片部分的代碼進行修改和替換,如把以下代碼:

  1. <img src="/wp-content/uploads/2014/02/hbzy1.gif" alt="hbzy" 
  2.  width="60" height="60" class="alignnone size-full wp-image-2100" /> 

輸出顯示的時候替換成如下代碼:

  1. <div class="gif-box"> 
  2. <img src="/wp-content/uploads/2014/02/hbzy1.jpg!static" 
  3.  _src="/wp-content/uploads/2014/02/hbzy1.jpg!static"  
  4. class="alignnone size-full wp-image-2100"  
  5. tsrc="/wp-content/uploads/2014/02/hbzy1.jpg" width="60" height="60" /> 
  6. <div class="gif-loading-box"> 
  7. <i class="gif-loading" style="display:none;"></i> 
  8. <i class="gif-play"></i> 
  9. </div> 
  10. </div> 

這里是為了動態gif圖片默認的時候不播放,點擊才播放,這個時候需要用到preg_match和正則表達式匹配圖片代碼,并用str_replace進行字符串的替換和修改,代碼如下:

  1. function gif_content($content) { 
  2.  $content = get_the_content (); 
  3.  $img_html = preg_match ( '/(<img[^>]+>)/i'$content$maches ); //獲取img圖片的html,如:<img src=".." class=".." width=""> //www.111cn.net 
  4.  $img_html = $maches [0]; 
  5.  
  6.  $img_width = preg_match ( '/width="[0-9]+"/i'$img_html$maches ); //獲取圖片寬度,如:width="32" 
  7.  $img_width = str_replace('='':'$maches[0]); 
  8.  $img_width = str_replace('"'''$img_width); 
  9.  $img_width = $img_width.'px'//替換成width:32px 
  10.  
  11.  $img_height = preg_match ( '/height="[0-9]+"/i'$img_html$maches ); 
  12.  $img_height = str_replace('='':'$maches[0]); 
  13.  $img_height = str_replace('"'''$img_height); 
  14.  $img_height = $img_height.'px'
  15.  
  16.  $img_name = preg_match ( '!http://.+.(?:jpe?g|png|gif)!Ui'$img_html$maches ); 
  17.  $img_name = $maches [0]; 
  18.  $img_html2 = str_replace ( 'src="' . $img_name . '"''src="' . $img_name . '!static" _src="' . $img_name . '!static' . '" tsrc="' . $img_name . '"'$img_html ); 
  19.  $img_html2 = '<div class="gif-box" style="'.$img_width.';'.$img_height.'">' . $img_html2 . '<div class="gif-loading-box"><i class="gif-loading" style="display:none;"></i><i class="gif-play"></i></div></div>';//在圖片的html代碼前后加上div 
  20.  
  21.  $content = str_replace ( $img_html$img_html2$content ); 
  22.  return $content
  23. add_filter('the_content''gif_content', 10);//wordpress的鉤子函數 

這里是用在wordpress的文章形式中的,當文章形式是image的時候,給這個文章形式下的圖片進行這樣的操作,另外在index.php中需要使用如下代碼:

  1. $format=get_post_format(); 
  2. if ('image'!=$format) { 
  3.  remove_filter('the_content''gif_content'); 
  4. get_template_part( 'content', get_post_format() ); 

這里要判斷一下如果是其他文章形式就移除這個鉤子,否則所有文章形式的圖片都被進行這樣的操作,本文講的是preg_match正則提取和替換字符串,以及wordpress的文章形式.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 马龙县| 通城县| 宁津县| 济宁市| 夏河县| 比如县| 万源市| 修文县| 达日县| 壶关县| 新巴尔虎左旗| 铜陵市| 钦州市| 招远市| 岫岩| 大宁县| 霸州市| 南开区| 巩留县| 盐池县| 英山县| 盖州市| 益阳市| 历史| 尉氏县| 四会市| 漠河县| 泽库县| 喀喇沁旗| 杭锦后旗| 乐平市| 神农架林区| 呼伦贝尔市| 博罗县| 肥城市| 乾安县| 商洛市| 横峰县| 玛沁县| 平顺县| 商河县|