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)'.
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:
explode()on a space character.(in the array elements and find the index.0to the next element of the element starting with(.implode()using a space character.So the above points will get you this code:
I have cached the value of
$arrbecause I am using it twice.Here’s the complete code with a couple of examples for the same:
In the above example, I have used these three strings:
And I am getting the following expected output:
Here’s a sandbox for the same: Get all words before and including the first element starting with
(.I hope this helps.