首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]替换字符串中存在的一个或多个链接

发布于 2024-09-22 11:35:47
0
193

字符串如下:

这是测试字符串https://www.baidu.com这是测试字符串

替换一个链接的方法:

public function getShortUrlWithContent(string $content = ""): string
{
    $pattern = '/https?:\/\/[\w\-\.\/?=&#%]+/i';
    if (preg_match_all($pattern, $content, $matches)) {
        $matchesUrl = $matches[0][0];
        $p = [];
        $postUrl = 'https://www.xxxxx.cn/api/getShortLink?url='.urlencode($matchesUrl);
        $res = ToolController::curl_post_json($postUrl, json_encode($p));
        if($res['code'] != 200 || $res['message'] != "SUCCESS"){
            Log::write('生成短链接失败,文本是'.$content.',时间:'.date('Y-m-d H:i:s'));
            $short_url = $matchesUrl;
        }else{
            $short_url = $res['data'];
        }
        $content = str_replace($matchesUrl, $short_url, $content);
    }
    return $content;
}
替换多个链接如下:
这是测试字符串https://www.baidu.com这是测试字符串https://***.cn这是测试字符串https://www.aliyun.com这是测试字符串
public function getShortUrlWithContent(string $content = ""): string
{
    $pattern = '/https?:\/\/[\w\-\.\/?=&#%]+/i';
    if (preg_match_all($pattern, $content, $matches)) {
        $matchesUrl = $matches[0];
        $p = $sendStr = [];
        foreach ($matchesUrl as $k => $v){
            $postUrl = 'https://www.xxxxx.cn/api/getShortLink?url='.urlencode($v);
            $res = ToolController::curl_post_json($postUrl, json_encode($p));
            if($res['code'] != 200 || $res['message'] != "SUCCESS"){
                Log::write('生成短链接失败,文本是'.$content.',时间:'.date('Y-m-d H:i:s'));
                $short_url = $v;
            }else{
                $short_url = $res['data'];
            }
            $sendStr[$v] = $short_url;
        }
        $content = strtr($content, $sendStr);
    }
    return $content;
}
以上~
评论
一个月内的热帖推荐
九秘
Lv.1种子选手

209

帖子

18

小组

362

积分

赞助商广告
站长交流