替换字符串中存在的一个或多个链接

字符串如下:

这是测试字符串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;
}
以上~
本文为 今天也想见到你 博客文章,转载无需和我联系,但请注明来自 今天也想见到你 博客 0925.wang
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇