2

How can i get every words before the word inside a ()

$str = "There are some (Cat) which are wild";
$str = "Animal (Cat) is a domestic pet";
echo implode(" ", array_slice(explode(" ", $str), 0, 2));

I want output as 'There are some (Cat)' and also 'Animal (Cat)'.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Abigail
  • 63
  • 5

1 Answers1

0

Assuming this is a continuation of your previous question, here’s what I’ll be doing.

I am going to follow these steps for solving this issue:

  1. Convert the string into array by using explode() on a space character.
  2. Create a mapper function for the array to get only the first characters.
  3. Search for the ( in the array elements and find the index.
  4. Slice the array from 0 to the next element of the element starting with (.
  5. Join all the elements of the array with implode() using a space character.

So the above points will get you this code:

<?php
  $str = "Animal (Cat) is a domestic pet";
  $arr = explode(" ", $str);
  echo implode(" ", array_slice($arr, 0, array_search('(', array_map("arrMapFirst", $arr)) + 1));

I have cached the value of $arr because I am using it twice.

Here’s the complete code with a couple of examples for the same:

<?php
  function arrMapFirst($a) {
    return $a[0];
  }

  $str = "Animal (Cat) is a domestic pet";
  $arr = explode(" ", $str);
  echo implode(" ", array_slice($arr, 0, array_search('(', array_map("arrMapFirst", $arr)) + 1));

  echo PHP_EOL;

  $str = "A Cute Animal (Cat) is a domestic pet";
  $arr = explode(" ", $str);
  echo implode(" ", array_slice($arr, 0, array_search('(', array_map("arrMapFirst", $arr)) + 1));

  echo PHP_EOL;

  $str = "An Angry Animal (Wolf) is not a domestic pet";
  $arr = explode(" ", $str);
  echo implode(" ", array_slice($arr, 0, array_search('(', array_map("arrMapFirst", $arr)) + 1));

In the above example, I have used these three strings:

  • Animal (Cat) is a domestic pet
  • A Cute Animal (Cat) is a domestic pet
  • An Angry Animal (Wolf) is not a domestic pet

And I am getting the following expected output:

  • Animal (Cat)
  • A Cute Animal (Cat)
  • An Angry Animal (Wolf)

Here’s a sandbox for the same: Get all words before and including the first element starting with (.

I hope this helps.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252