siwelis Posted April 14, 2010 Share Posted April 14, 2010 How would I keep only the numbers at the end when "img_" is a constant? img_63 img_65 img_67 Thank you Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted April 14, 2010 Share Posted April 14, 2010 $str = "img_63"; $num = substr($str, 4); echo $num; Quote Link to comment Share on other sites More sharing options...
cags Posted April 14, 2010 Share Posted April 14, 2010 ...or... echo $output = str_replace('img_', '', $input); ...or... preg_match('#([0-9]+)$#', $input, $out); echo $output = $out[1]; ...or about a dozen other ways. Quote Link to comment Share on other sites More sharing options...
siwelis Posted April 14, 2010 Author Share Posted April 14, 2010 I ended up using a bit of both codes: if(str_replace('img_', '', $key)){ //to only change the $key when img_ is present $key = substr($key, 4); //remove img_ from each instance echo $key."<br />"; echo "<br />Image ".$key." is ON!<br />"; } Thank you! Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted April 14, 2010 Share Posted April 14, 2010 A better if statement would be to use strpos Quote Link to comment Share on other sites More sharing options...
cags Posted April 14, 2010 Share Posted April 14, 2010 Ken2k7 has a point, but why do you care if it's there, by simply replacing all instances of 'img_' with '', if there are non in the string it won't replace any, if it is in the string it will be replaced, I'm not sure I see the point of checking first. Quote Link to comment Share on other sites More sharing options...
siwelis Posted April 14, 2010 Author Share Posted April 14, 2010 Ken2k7 has a point, but why do you care if it's there, by simply replacing all instances of 'img_' with '', if there are non in the string it won't replace any, if it is in the string it will be replaced, I'm not sure I see the point of checking first. I always need "img_" replaced, but there are other things in the array that do not have img_ and I need them left alone... if(str_replace('img_', '', $key)){ The above piece of code didn't do as I wanted... whether it actually replaces anything or not, it carries out the following code. Quote Link to comment Share on other sites More sharing options...
siwelis Posted April 14, 2010 Author Share Posted April 14, 2010 I tried it with strpos and it executed everything in between the brackets whether it actually did anything or not... This worked though: if(substr_count($key,'img_') == 1){ //if occurences of "img_" = 1 $key = substr($key, 4); //remove img_ echo $key."<br />"; //verify removal echo "Image ".$key." is ON!<br /><br />"; //party time } Thank you again! Quote Link to comment 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.