Forum Moderators: coopster
$someString = "Hello Webmaster World dot com";
$var = explode(" ", $someString);
//now I have the array:
// var[0] --> Hello
// var[1] --> Webmaster, etc...
How do I access the first character in each new array element? Since the strings are stored in an array I can't access them like normal variable strings.
example:
$temp = "hello";
echo "First character of temp is: $temp[0] <br/>";
But if they are stored in arrays how can I access the first char of the string (without storing it in a new variable)?
example:
$temp = var[0];
echo "First character of temp is: $temp[0] <br/>";
$var = explode(" ", $someString);
//now I have the array:
// var[0] --> Hello
// var[1] --> Webmaster, etc...
print_r($var); // just watch the array load perfectly
//echo substr($var[1], 0, 1); // for single line
for ($i=0; $i<sizeof($var); $i++) // for the array
{
echo "<br>".substr($var[$i], 0, 1)."<br>";
}
?>
$var[0][0]should work - Strings are just Arrays of characters ;)
For this problem, you can also do something like:
$input = "Hello Webmaster World dot com";
preg_match_all("/\b([\w])[\w]+/", $input, $regs);
print_r($regs[1]);
;)
Or preg_match_all("/\b(\w)/", $input, $regs);
You don't need the square backets for single character definitions, its used for grouping (as opposed to normal brackets which are used to specify a particular pattern). Ala [\s\w]+ will match spaces or word characters, whereas (\s\w)+ only matches alternating spaces and word characters