一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2014-03-01 编辑:简简单单 来源:一聚教程网

把以下代码:

 代码如下 复制代码

hbzy  width="60" height="60" class="alignnone size-full wp-image-2100" />

输出显示的时候替换成:

 代码如下 复制代码


 _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" />




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

 代码如下 复制代码

function gif_content($content) {
 $content = get_the_content ();
 $img_html = preg_match ( '/(]+>)/i', $content, $maches ); //获取img图片的html,如: //www.111com.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 = '

' . $img_html2 . '
';//在图片的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的文章形式。

热门栏目