Home > database >  fetch first 2 words along with symbols
fetch first 2 words along with symbols

Time:04-23

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));

CodePudding user response:

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

CodePudding user response:

It's much easier. Just tokenize on a space twice:

echo strtok($_POST['str'], ' ') . ' ' . strtok(' ');
  • Related