首页 小组 问答 话题 好文 素材 用户 唠叨 我的社区

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

九秘Lv.1种子选手
2024-09-22 11:35:47
0
44

字符串如下:

这是测试字符串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;
}
以上~
九秘
九秘

30 天前

签名 : 我常驻在>https://www.huaqu.club/ask   44       0
评论
站长交流