'How to get every words before () in a string
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)'.
Solution 1:[1]
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:
- Convert the string into array by using
explode()
on a space character. - Create a mapper function for the array to get only the first characters.
- Search for the
(
in the array elements and find the index. - Slice the array from
0
to the next element of the element starting with(
. - 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. ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Praveen Kumar Purushothaman |