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
https://forums.phpfreaks.com/topic/260512-strpos-wont-accept-whitespaces/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.