字符串如下:

这是测试字符串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://sina.com.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;
}

以上~