Jump to content

strpos() won't accept whitespaces?


MrAshburn

Recommended Posts

Hy ya'll!

 

I've been trying to programatically read a string, but with no success.

 

function get_between($input, $start, $end) {
  $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
  return $substr;
}

$string =  'open -greetings hello -bye seeya';
echo get_between($string, '-greetings ', ' -bye'); // Output: hello
echo get_between($string, '-greetings ', ' -'); // Outputs nothing
echo get_between($string, '-greetings ', ' '); // Outputs nothing
}

 

It turns out that I don't know if "-bye" will always follow the value of "-greetings", so I can't call everything in between like the first way even tough it works fine in this example. Given that those values will always be a single word, I can use a whitespace as a delimiter to the right, but for some reason it won't return anything whatsoever, not even an error code.

 

Any ideas how to get it done?

 

Txs a bunch!

Link to comment
Share on other sites

Hello there,

 

As for the subject: strpos does accept whitespaces. your substr's length parameter is just wrong since you're getting the length from the whole string.

 

Anyways, my version of the function:

function get_between($input, $start, $end) {
$start = substr($input, strpos($input,$start) + strlen($start));
return substr($start, 0, strpos($start, $end));
}

Should work just neatly.

 

There's also a better way to get the content between two clues:

function get_between($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

 

Hope this helps.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.