国产探花免费观看_亚洲丰满少妇自慰呻吟_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的文章形式.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新沂市| 彭州市| 方城县| 古浪县| 安新县| 固阳县| 白河县| 南华县| 文山县| 黄骅市| 新沂市| 东源县| 彰化县| 固阳县| 通河县| 于都县| 内乡县| 杭锦旗| 武定县| 界首市| 克什克腾旗| 保靖县| 长垣县| 锡林浩特市| 华宁县| 玉环县| 堆龙德庆县| 双鸭山市| 高邑县| 寿光市| 独山县| 晋城| 林甸县| 兰坪| 彩票| 宜城市| 绥宁县| 鸡东县| 十堰市| 花莲县| 肇州县|