Reputation: 28148
I am trying to "extract" the link part from a tweet message:
$tweet = "Testing a tweet with a link https://t.co/h4C0aobVnK in the middle"
I have a function which doesn't quite work but I'm not sure why. I need to get the link part, so I need everything between https://
and the space
The result I want would be: t.co/h4C0aobVnK
This is the function:
function dataBetween($string, $start, $end){
$sp = strpos($string, $start)+strlen($start);
$ep = strpos($string, $end)-strlen($start);
$data = trim(substr($string, $sp, $ep));
return trim($data);
}
Here's how it's called:
$link = dataBetween($tweet,'https://',' ');
But the result I get is not what I expected:
t.co/h4C0aobVnK in the middl
Where did I go wrong?
Is there a better way to extract the link part from $tweet
? It will always start with https://.
Upvotes: 0
Views: 55
Reputation: 7552
Well, change this:
$ep = strpos($string, $end)-strlen($start);
To:
$ep = strpos($string, $end, $sp) - strlen($string);
Passing the third parameter of strpos (offset) it will start from where the link started, and get the first ' ' after that.
Upvotes: 0
Reputation: 11693
Use
$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
if(preg_match("/^$regex$/", $tweet , $m))
var_dump($m);
Upvotes: 0
Reputation: 33196
You should use regular expressions for this. This might look complicated, but once you start using them, there is no going back. ;)
preg_match_all("/https:\/\/(.*?)\s/", $string, $matches);
print_r($matches);
Upvotes: 1
Reputation: 83
$ep = strpos($string, $end)-strlen($start);
change to
$ep = strpos($string, $end)-strlen($end);
Just a misstype.
Upvotes: 0
Reputation: 494
strpos finds the first occurrence of a string. For $ep, you should start looking AFTER the $sp, not from the beginning of the string
$ep = strpos($string, $sp)-strlen($end);
also, you could use a regular expression like this |www://([^ ]+)|i *http is not allowed in the comment box, so just replace ww with that
Upvotes: 0