好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

wordpress中preg_match正则提取和替换字符串 - WordPr

wordpress中preg_match正则提取和替换字符串

在wordpress显示文章的时候,如果文章形式是图片的文章,需要把里面的图片部分的代码进行修改和替换,如把以下代码:

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

输出显示的时候替换成如下代码:

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

这里是为了动态gif图片默认的时候不播放,点击才播放,这个时候需要用到preg_match和正则表达式匹配图片代码,并用str_replace进行字符串的替换和修改,代码如下:

function  gif_content( $content ) {    $content  = get_the_content ();    $img_html  = preg_match (  '/(<img[^>]+>)/i' ,  $content ,  $maches  );  //获取img图片的html,如:<img src=".." class=".." width=""> //www.111cn.net     $img_html  =  $maches  [0];      $img_width  = preg_match (  '/width="[0-9]+"/i' ,  $img_html ,  $maches  );  //获取图片宽度,如:width="32"     $img_width  =  str_replace ( '=' ,  ':' ,  $maches [0]);    $img_width  =  str_replace ( '"' ,  '' ,  $img_width );    $img_width  =  $img_width . 'px' ;  //替换成width:32px       $img_height  = preg_match (  '/height="[0-9]+"/i' ,  $img_html ,  $maches  );    $img_height  =  str_replace ( '=' ,  ':' ,  $maches [0]);    $img_height  =  str_replace ( '"' ,  '' ,  $img_height );    $img_height  =  $img_height . 'px' ;      $img_name  = preg_match (  '!http://.+.(?:jpe?g|png|gif)!Ui' ,  $img_html ,  $maches  );    $img_name  =  $maches  [0];    $img_html2  =  str_replace  (  'src="'  .  $img_name  .  '"' ,  'src="'  .  $img_name  .  '!static" _src="'  .  $img_name  .  '!static'  .  '" tsrc="'  .  $img_name  .  '"' ,  $img_html  );    $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       $content  =  str_replace  (  $img_html ,  $img_html2 ,  $content  );    return   $content ;  }  add_filter( 'the_content' ,  'gif_content' , 10); //wordpress的钩子函数  

这里是用在wordpress的文章形式中的,当文章形式是image的时候,给这个文章形式下的图片进行这样的操作,另外在index.php中需要使用如下代码:

$format =get_post_format();  if  ( 'image' != $format ) {   remove_filter( 'the_content' ,  'gif_content' );  }  get_template_part(  'content' , get_post_format() ); 

这里要判断一下如果是其他文章形式就移除这个钩子,否则所有文章形式的图片都被进行这样的操作,本文讲的是preg_match正则提取和替换字符串,以及wordpress的文章形式.

查看更多关于wordpress中preg_match正则提取和替换字符串 - WordPr的详细内容...

  阅读:54次