开发者

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 -> bloo开发者_开发技巧p
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.


You could use preg_match_all with something like (just a quick draft...):

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜