Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading