2023-05-12 开启多语言插件支持……

截取微博长度,替换微博url

php 苏 demo 2647℃ 0评论
微壹佰网,新浪微博,腾讯微博等等都需要对微博内容、字数进行处理,以下是替换内容内URL,图片,截取微博长度的方法
 /* 替换掉原来的 url 地址 */
$result[‘text’] = preg_replace(“/(http:\/\/[\w\d\.\/]+)/i”, “<a href=’\\1′ target=’_blank’>\\1<a>”, $result[‘text’]);
$new = preg_replace(“/(http|https):\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z\$\.\+\!\_\*\(\)\/\,\:;@&=\?~#%]*)*/i”, “http://0123456789.cn”, $tweet);
$striped = preg_replace(“/(http|https):\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z\$\.\+\!\_\*\(\)\/\,\:;@&=\?~#%]*)*/i”, “”, $tweet);
 /* 内容过长,进行截取  */
$repost_text = $this->tweetSubString($con, $len);
/**
     * 截取微博长度
     *  汉字算一个长度
     *  两个英文字符算一个长度
     *
     */
    function tweetSubString($tweet, $length)
    {
        $len = 0;
        $char_len = 0;
        $last_pos = 0;
        for($i = 0; $i < strlen($tweet); $i++)
        {
            $char = substr($tweet, $i, 1);
            $ord = ord($char);
            if ($ord < 128)
            {
                $char_len = ($char_len + 1) % 2;
                if ($char_len > 0) {
                    $len++;
                }
                else {
                    $last_pos = $i;
                }
            }
            else
            {
                if ($ord > 191) /* utf8 起始字符 */
                {
                    $last_pos = $i – 1;
                    $len++;
                }
            }//
            if ($len > $length) {
                break;
            }
        }//for
        //return substr($tweet, 0, max($last_pos, 0));
        return substr($tweet, 0, $last_pos + 1);
    }

php 替换文章内容HTML标签img的URL路径
<?php
//要替换的内容
$content = ‘dawdawdaw<p>ssss</p><img alt=”” src=”js/fckeditor/UserFiles/image/F201005201210502415831196.jpg” width=”600″ height=”366″><br><br>dawdawdawd<br><br>dawdawdaw<img alt=”” src=”js/fckeditor/UserFiles/image/33_avatar_middle.jpg” width=”120″ height=”120″>dawdawdaw’;
//提取图片路径的src的正则表达式
preg_match_all(“/<img(.*)src=\”([^\”]+)\”[^>]+>/isU”,$content,$matches);
$img = “”;
if(!empty($matches)) {
//注意,上面的正则表达式说明src的值是放在数组的第三个中
$img = $matches[2];
}else {
$img = “”;
}
if (!empty($img))
{
$img_url = “”;
$patterns= array();
$replacements = array();
foreach($img as $imgItem){
$final_imgUrl = $img_url.$imgItem;
$replacements[] = $final_imgUrl;
$img_new = “/”.preg_replace(“/\//i”,”\/”,$imgItem).”/”;
$patterns[] = $img_new;
}
//让数组按照key来排序
ksort($patterns);
ksort($replacements);
}
//替换内容
$vote_content = preg_replace($patterns, $replacements, $content);
echo $vote_content;
?>
打赏

转载请注明:苏demo的别样人生 » 截取微博长度,替换微博url

   如果本篇文章对您有帮助,欢迎向博主进行赞助,赞助时请写上您的用户名。
支付宝直接捐助帐号oracle_lee@qq.com 感谢支持!
喜欢 (0)or分享 (0)