Search code examples
phpexplodeimplode

fetch first 2 words along with symbols


I am trying to fetch the first 2 words from a sting, the first word Animal and second word is (Cat) my current code does fetch it but the () brackets gets ignore I want to fetch exactly like on string Animal (Cat).

echo implode(' ', array_slice(str_word_count($_POST['str'], 2), 0, 5));

Solution

  • You can use array_slice to get the first two words and then use implode to join them:

    <?php
      $str = "Animal (Cat) is a domestic pet";
      echo implode(" ", array_slice(explode(" ", $str), 0, 2));
    

    I get the output as:

    Animal (Cat)
    

    Here's a sandbox: https://sandbox.onlinephpfunctions.com/c/a2c44