Search code examples
phptrimstrpos

Getting a sub string between two different delimiters


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://.


Solution

  • 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);