AdRock Posted March 25, 2009 Share Posted March 25, 2009 I am trying to cut down a string up to a certain point but it's not working what i want it to output is test/another-test/here and anything else is stripped off <?php $string = "test/another-test/here/end"; $string = substr($string,0,stristr($string,'end')); echo $string; ?> Link to comment https://forums.phpfreaks.com/topic/151148-solved-stripping-down-part-of-a-string/ Share on other sites More sharing options...
unska Posted March 25, 2009 Share Posted March 25, 2009 If the string is static you should use (http://php.net/strpos) but if it's dynamic, you could either use regexp (http://www.regular-expressions.info) or the example below. <?php $string = "test/another-test/here/end"; $toFind = "end"; $position = strpos($string, $toFind); if ($position !== false) { echo substr($string, 0, $position); } ?> Link to comment https://forums.phpfreaks.com/topic/151148-solved-stripping-down-part-of-a-string/#findComment-794018 Share on other sites More sharing options...
steelaz Posted March 25, 2009 Share Posted March 25, 2009 If you want to drop last element, there's another way of doing it: <?php $string = "test/another-test/here/end"; // Turn string into array $array = explode('/', $string); // Remove last array element array_pop($array); // Glue array into string echo implode('/', $array); ?> Link to comment https://forums.phpfreaks.com/topic/151148-solved-stripping-down-part-of-a-string/#findComment-794019 Share on other sites More sharing options...
dubc07 Posted March 25, 2009 Share Posted March 25, 2009 <?php ///try this $string = str_replace('end',' '); //if you need to cut down more of the script try putting content after the end into a variable ///example $end='posted content'; $string1 = str_replace('$end',' '); $string = "test/another-test/here/$string1"; ?> Link to comment https://forums.phpfreaks.com/topic/151148-solved-stripping-down-part-of-a-string/#findComment-794021 Share on other sites More sharing options...
AdRock Posted March 25, 2009 Author Share Posted March 25, 2009 I managed to fix it like this <?php $string = "test/another-test/here/end"; if(stristr($string,"here")) { $string = substr($string,0,strrpos($string,'/')); } echo $string; ?> Link to comment https://forums.phpfreaks.com/topic/151148-solved-stripping-down-part-of-a-string/#findComment-794038 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.