MrAshburn Posted April 7, 2012 Share Posted April 7, 2012 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! Quote Link to comment https://forums.phpfreaks.com/topic/260512-strpos-wont-accept-whitespaces/ Share on other sites More sharing options...
noXstyle Posted April 7, 2012 Share Posted April 7, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/260512-strpos-wont-accept-whitespaces/#findComment-1335217 Share on other sites More sharing options...
MrAshburn Posted April 7, 2012 Author Share Posted April 7, 2012 Yay, that did the trick! I'm using your version from now on as that code looks cleaner and effective. Thank you so much, yo! You saved my weekend! Quote Link to comment https://forums.phpfreaks.com/topic/260512-strpos-wont-accept-whitespaces/#findComment-1335224 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.