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.
It appears from your examples following should work for you:
$tweet = preg_replace('~\bhttps://\S+~', $embedded_url, $tweet);
Usually I use strstr for find string started with https://
$url = strstr($str, "https://");
then use strpos for find end. If found space then substr string by this length. Else variable already contains url.
$pos = strpos($url, " ");
if ($pos > 0) {
$url = substr($url, 0, $pos)
}