php function that return initials?

chuwen25

New member
two questions

how to write a php function that when input a string, the function will return a new string with the first letters of all the words from the input string?

how to write a same kind of function as the above, but instead of returning initials, it returns the exact string with underscopes replacing any space in the input string?

for example
$var = "ask yahoo";
returnInitial($var);
returnUnderscope($var);

and it will return something like "ay" and "ask_yahoo"
 
The second one is much easier than the first, because PHP has a built-in function for the the second, but not the first.

for returnInitial($var) I suggest using "explode" to break apart the string into several strings using space as a delimiter. Then you can loop through each and take its first letter:

$var_split = explode(" ", $var);
foreach ($var_split as $temp) {
return $temp{0};
}

for returnUnderscore($var) I suggest using the built in str_replace() function like so:

return str_replace(" ","_",$var,$i);

($i merely counts how many such replacements you make)
 
Back
Top