webdevdea Posted July 12, 2013 Share Posted July 12, 2013 I know the problem is here I cant understand what to put in there to get the value of the second character when something is typed into the text field also how could I acces the value of $str in my print statement? Please and thank you .. echo substr($str, 3,-1); f (filter_has_var(INPUT_POST, "color")) { //work with the form $color = filter_input(INPUT_POST, "color"); $str = filter_input(INPUT_POST, "color"); echo substr($str, 3,-1); print"<h2> Your word was $color </h2>"; Link to comment https://forums.phpfreaks.com/topic/280112-second-letter-of-a-text-field/ Share on other sites More sharing options...
Psycho Posted July 13, 2013 Share Posted July 13, 2013 Did you read the manual for substr()? It's pretty straightforward for what you want. substr($str, 1, 1); The first number represent the index of the character yuo want to start at (first character is at index 0, so the 2nd is at index 1). The second number represents the number of characters you want to obtain. Link to comment https://forums.phpfreaks.com/topic/280112-second-letter-of-a-text-field/#findComment-1440540 Share on other sites More sharing options...
kicken Posted July 13, 2013 Share Posted July 13, 2013 For single character access, you can also just treat the string as an array an index into it: $secondChar = $str[1]; //0-based Link to comment https://forums.phpfreaks.com/topic/280112-second-letter-of-a-text-field/#findComment-1440548 Share on other sites More sharing options...
Irate Posted July 13, 2013 Share Posted July 13, 2013 To add more to the above method kicken provided, strings should be immutable "objects", means that you can read their value like an array, but you cannot set the index to something else. Example. <?php $str = "This is an example string."; $splitstr = $str[0]; // "T" $str[0] = "D"; // fails echo($str[0]); // still displays "T" ?> Link to comment https://forums.phpfreaks.com/topic/280112-second-letter-of-a-text-field/#findComment-1440603 Share on other sites More sharing options...
kicken Posted July 13, 2013 Share Posted July 13, 2013 To add more to the above method kicken provided, strings should be immutable "objects", means that you can read their value like an array, but you cannot set the index to something else.Whether they should be immutable or not is debatable. The fact is that they are not however, you can change individual characters through array access. <?php $str = 'Blah'; var_dump($str[1]); //string(1) "l" $str[1] = 'a'; var_dump($str[1], $str); //string(1) "a" //string(4) "Baah" Link to comment https://forums.phpfreaks.com/topic/280112-second-letter-of-a-text-field/#findComment-1440618 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.