You want to extract part of a string, starting at a particular place in the string. For example, you want the first eight characters of a username entered into a form.
Use substr($string, $start, $length) to select your substring. If $start and $length are positive, substr() returns $length characters in the string, starting at $start. The first character in the string is at position 0.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $username = 'John Doe'; echo "Extract $username with start=5: ", substr($username, 5), "<br />"; echo "Extract $username with start=2 and length=4: ", substr($username, 2, 4), "<br />"; echo "Extract $username with start=20: ", substr($username, 20), "</br />"; echo "Extract $username with start=5 and length=5: ", substr($username, 5, 5), "<br />"; echo "Extract $username with start=-5: ", substr($username, -5), "<br />"; echo "Extract $username with start=-5 and length=5: ", substr($username, -5, 5), "</r />"; echo "Extract $username with start=-10: ", substr($username, -10), "<br />"; echo "Extract $username with start=5 and length=-5: ", substr($username, 5, -5), "<br />"; echo "Extract $username with start=-5 and length=-5: ", substr($username, -5, -5), "<br />"; ?> </p> </body> </html> |