0

I have this string "PAX 098-5503268037/ETAI/USD107.75/15MAY20/KTMVS31KL/10303171" and would like to extract the USD107.75.I have this function:

Here:

$str = PAX 098-5503268037/ETAI/USD107.75/15MAY20/KTMVS31KL/10303171;
$from = '/ETAI';
$to = '/';

    public function getStringBetween($str,$from,$to)
    {
        $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
        return substr($sub,0,strpos($sub,$to));
    }

The function only return an empty string.

What am I missing?

Thanks

1
  • 2
    Maybe explode by / and take 3rd element? Commented May 15, 2020 at 11:53

1 Answer 1

2

If you do a bit of debugging...

public function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    echo $sub.PHP_EOL;
    return substr($sub,0,strpos($sub,$to));
}

you will see the interim output is

/USD107.75/15MAY20/KTMVS31KL/10303171

as you then look for the first / and extract up to that, that is the first character.

A simple solution to what you already have is to add +1 in the start position...

public function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from)+1,strlen($str));       
    return substr($sub,0,strpos($sub,$to));
}

Alternatively, you can as u_mulder indicated, explode() on / and then extract the part you are after...

echo explode("/", $str)[2];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.