简体   繁体   中英

Split string between two characters?

Ok this one should be incredibly easy, but I don't know what I'm looking for...

I want to split a string up between two characters

$string = "blah blah blah (blorp) blah blah (bloop) blah blah (bam)";

retruns :

array
1 -> blorp
2 -> bloop
3 -> bam

I dont need any of the blah blahs just everything within parenthesis.

Thanks!

Arthur

You can do this with a regular expression:

$string = "blah blah blah (blorp) blah blah (bloop) blah blah (bam)";
preg_match_all("/\((.*?)\)/", $string, $result_array);

print_r( $result_array[1] ); // $result_array[0] contains the matches with the parens

This would output:

Array
(
    [0] => blorp
    [1] => bloop
    [2] => bam
)

My regular expression uses a non-greedy selector: (.*?) which means it will grab as "little" as possible. This keeps it from eating up all the ) and grabbing everything between the opening ( and the closing ) how ever many words away.

您可以使用preg_match_all之类的东西(只是快速草稿...):

preg_match_all("|\([^)]+\)|", $string, $result_array);

all using regex, here's one without regex

$string = "blah blah blah (blorp) blah blah (bloop) blah blah (bam)";
$s = explode(")",$string);
foreach ( $s as $k=>$v ){
    $m= strpos($v,"(" );
    if ($m){
        print substr( $v, $m+1  )  . "\n"  ;
    }
}

If you want everything in parenthesis, then you should use regular expressions. In your case, this will do the thick:

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

http://php.net/manual/en/function.preg-match-all.php

$matches = array();
$num_matched = preg_match_all('/\((.*)\)/U', $input, $matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM