Sugato Sengupta Sugato Sengupta - 4 months ago 6
PHP Question

Separate string within bracket where number of bracket varies

This is my first question here and I am messed up with strings. I have some strings in the following format:

I will be here (I may or may not be here) (30-Apr-2013)
I am still here (15-Feb-2013)
I am still here(I may not be here) (I may not be here) (9-Apr-2013)


I need to separate the date from the name. As you can see, the number of brackets may vary, but I need the last one only ( rest of the string will be treated as name).

Expected output:

1. array( 0=> 'I will be here (I may or may not be here)' , 1=> '30-Apr-2013' )
2. array( 0=> 'I am still here' , 1=> '15-Feb-2013' )
3. array( 0=> ' I am still here(I may not be here) (I may not be here)' , 1=> '9-Apr-2013' )


What is the best way to achieve this?

Answer

You can use strrpos to find the last occurrence of ( and then you can use substr and trim to get the sub-strings and trim them to the result you want.


E.g.

/**
 * Return an array with the "name" as the first element and
 * date as the second.
 */
function fun($string)
{
    $datePos = strrpos($string, '(');
    return array (
        trim(substr($string, 0, $datePos - 1)), trim(substr($string, $datePos), ' ()')
    );
}
Comments