0

Question can be unclear, but here is what I want to achieve.

I have following string:

$input  = 'foo_bar_buz_oof_rab';

I need to get in the output following string:

$output = 'fbbor';

As you can see, the point is to explode string with _ and get the first letters of the substrings. What is the best method to get it ? Regex, explode and loop over substrings ?

4
  • Not sure what you want to do with that, but if you plan to transform every first letter into capitals, theres a special function in php called ucfirst() || php.net/manual/en/function.ucfirst.php Commented Dec 9, 2013 at 10:53
  • I just want to get first letters as described above. No transformation will be involved here. Commented Dec 9, 2013 at 10:54
  • @hsz What about trying the solutions answered? Commented Dec 9, 2013 at 10:55
  • Kay, then i suppose the easiest way will be if you just explode the string and use the substr method on each row of the array which you get from explode, like described below. Commented Dec 9, 2013 at 10:55

3 Answers 3

1
$words = explode("_", "BLA_BLA_BLA_BLA");
$acronym = "";

foreach ($words as $w) {
  $acronym .= $w[0];
}

You mean this?

Sign up to request clarification or add additional context in comments.

Comments

0

you can use and substr function to achieve this

like below

$str = "foo_bar_buz_oof_rab";

$arr = explode("_",$str);
$new_str = '';
foreach($arr as $a){

  $new_str .= $new_str .substr($a,0,1);

}

echo $new_str;

This will give your desired output

1 Comment

This will double your $new_str every time you iterate through the loop, as you already use the .= concat operator.
0

I also did it with:

$output = implode(array_map(function($k){ return $k[0]; }, explode('_', $input)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.