0

I would like to extract whatever text comes inside (). Desired output should be "Name", "Turkey". I have tried this

    $input = "This is (Name). I live in (Turkey). and so on with other brackets as well".
    $unit = extract_unit($input, '(', ')');
    echo $unit;

    function extract_unit($string, $start, $end) {
        $pos = stripos($string, $start);
        $str = substr($string, $pos);
        $str_two = substr($str, strlen($start));
        $second_pos = stripos($str_two, $end);
        $str_three = substr($str_two, 0, $second_pos);
        $unit = trim($str_three); // remove whitespaces
        return $unit;
    }

But Only getting first output which is "Name" but require "Turkey" and so on values whatever comes in brackets if the length of text increases.

Harmeet Singh
  • 43
  • 1
  • 1
  • 8
  • Maybe you should try to use a regex expression to get what you want? And since it will always be between `(` and `)`, I think you can forget the `$start` and `$end` arg in your function, no? – Mickaël Leger May 31 '18 at 07:44
  • 1
    Possible duplicate of [Regular Expression to find a string included between two characters while EXCLUDING the delimiters](https://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud) – Mickaël Leger May 31 '18 at 07:45
  • 1
    Possible duplicate of [How to get a substring between two strings in PHP?](https://stackoverflow.com/questions/5696412/how-to-get-a-substring-between-two-strings-in-php) – pavankguduru May 31 '18 at 07:45

1 Answers1

0

Try using this:

$string = 'This is (Name). I live in (Turkey). and so on with other brackets as well';

preg_match_all('/\((.*?)\)/i', $string, $matches);

print_r($matches[1]);
Phil Cross
  • 9,017
  • 12
  • 50
  • 84