2

suppose i have a set of strings formatted in a way:

$string1 = "(substring1) Hello";
$string2 = "(substring2) Hi";

how do i get the inside of '()' as a single string. I know this is possible by using:

$substring = explode( ")",$string1 );

but then i'm left with $substring[0] containing "(substring", and $substring[1] containing the rest. Is there a fast wat to get the inside of '()'? thanks i know it's a no brainer question.

1
  • Just a note. explode is used when you want to split a string into multiple parts. What you want here is to extract one string from another string according to a certain pattern. Thus preg_match(_all) is the way to go. Hanky Panky's answer is exactly how I would have solved this. Commented Sep 9, 2013 at 7:44

3 Answers 3

3

explode might need a workaround because ( and ) are different. A simple regex will get the job done.

$string1 = "(substring1) Hello";
preg_match('#\((.*?)\)#', $string1, $match);  // preg_match_all if there can be multiple such substrings
print $match[1];
Sign up to request clarification or add additional context in comments.

Comments

1

Well, if you want to keep the explode, do this with your substring[0]:

$substring[0] = substr($substring[0],1);

this will return you the portion after "(".

Else, use a regular expression to match what you need!

Edit:

Check the above answer to see the regular expression solution, this guy provided you a great way to solve your problem! :]

Comments

0

If you want to use explode to do this job:

<?php
$string1 = "(substring1) Hello";

function between($delimiter1, $delimiter2, $subject)
{
    $arr = explode($delimiter2, $subject);
    if (!$arr || empty($arr) || count($arr) == 1)
    {
        return '';
    }
    $oldStr = trim(array_shift($arr));
    $arr = explode($delimiter1, $oldStr);
    if (!$arr || empty($arr))
    {
        return '';
    }
    return trim(array_pop($arr));
}

$result = between('(', ')', $string1);
echo $result, "\n";

But I suggest you use preg_match function, which is use regular expression to match string, more powerful and complicated:

<?php
$string1 = "(substring1) Hello";

$pattern = '/\((.*?)\)/';
$match = array();
preg_match($pattern, $string1, $match);
echo $match[1], "\n";

1 Comment

more powerful and complicated:: Is that really more complicated? That regex seems so simple as compared to that complicated explode code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.