1

I would like to generate code which will recognize how many words we have in one string. If there is one word, to read first 3 characters but if there are more than one word, then to choose first character of each word.

I have tried code below, but this will recognize and take only first character of each word, so if there is only one word, it will take only one character.

<?php
$category = $title;

    $category = explode(" ", $category);

    foreach ($category as $value) {
        echo $firstLetter = $value[0];
    }
?>

1 Answer 1

0

Try this using sub_str:

<?php
  $category = $title;

  $category = explode(" ", $category);
  if (is_array($category)) {
    if (count($category) == 1) {
       echo substr($category[0], 0, 3);           
    } else {
        foreach ($category as $value) {
           echo $value[0];
       }
    }
  }
?>
1
  • Perfect, that worked. is it possible to make $title to be recognized on the way: 1. $title = that works perfectly well 2. $title = category number two tested ... ... ... code will recognize "that works perfectly well" and that to be replaced with first characters TWPW code will recognize "category number two tested" and that to be replaced with first characters CNTT ... ... so if I have few $title strings, I can write full name to be replaced with short name
    – stvlada
    Dec 5, 2015 at 20:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.