doumiao0498 2014-11-10 16:12
浏览 36
已采纳

用变量替换字符串的一部分,但使用复杂的分隔符

I know that I can use str_replace to replace certain things quite easily in a string. But I'm completely stuck with how to do it when I cannot find a really easy delimiter for the content.

I have strings which can have links anywhere in them, e.g

$tweet = "Testing a tweet with a link https://t.co/h4C0aobVnK in the middle";

or

$tweet = "Testing a tweet with a link: https://t.co/dgg0eA3uIt";

I have a variable $embedded_link which contains a prettified <a> tag ready to go. E.g

<a href="https://dev.twitter.com/oauth/application-only" target="_blank">dev.twitter.com/oauth/applicat…</a>

I need to replace the link, which always starts with https:// and is defined by ending when there is a next space, and replace it with $embedded_url

So this:

$tweet = "Testing a tweet with a link https://t.co/h4C0aobVnK in the middle";

Becomes this:

$tweet = "Testing a tweet with a link <a href="https://dev.twitter.com/oauth/application-only" target="_blank">dev.twitter.com/oauth/applicat…</a> in the middle";

How would you go about this? I was thinking of using https:// and a space as the delimiters, but it's possible for there to be no space at the end of the string.

  • 写回答

2条回答 默认 最新

  • dongying7847 2014-11-10 16:32
    关注

    It appears from your examples following should work for you:

    $tweet = preg_replace('~\bhttps://\S+~', $embedded_url, $tweet);
    

    RegEx Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)