some examples using substr(),
extracting the first, last, n chars of a
string.
reverse a string or see how many times a char is used in a string.
“substring examples” makes use of the built-in PHP functions
explode( ),
count( ),
substr( ),
strlen( ),
array_key_exists( ),
ksort( ),
join( ),
array_reverse( ) and
print_r( ).
01 <?php
02
03 echo '
04 <form method="post" action="./">
05 <input type="text" name="word" />
06 <input type="submit" value="see" />
07 </form>';
08
09 if(!empty($_POST['word']))
10 {
11 $str = $_POST['word'];
12
13 $char['original'] = $str;
14
15 $char['words'] = explode(' ',$str);
16
17 $char['word_count'] = count($char['words']);
18
19 $char['first_char'] = substr($str,0,1);
20
21 $char['last_char'] = substr($str,-1);
22
23 $char['all_but_first_char'] = substr($str,1);
24
25 $char['all_but_last_char'] = substr($str,0,-1);
26
27 $char['char_repeat'] = array();
28
29 for($x = 0; $x < strlen($str); $x++)
30 {
31 $char['chars'][] = substr($str,$x,1);
32
33 if(!array_key_exists($str{$x},$char['char_repeat'])) $char['char_repeat'][$str{$x}] = 0;
34
35 $char['char_repeat'][$str{$x}]++;
36 }
37
38 $char['char_count'] = strlen($str);
39
40 ksort($char['char_repeat']);
41
42 $char['reverse'] = join('',array_reverse($char['chars']));
43
44 echo '<pre>';
45 print_r($char);
46 echo '</pre>';
47 }
48
49 ?>