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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?