Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get first portion of string

Status
Not open for further replies.

ArtWerk

Programmer
Jul 31, 2006
66
US
How do I extract only a portion of a string between two characters?

I.e.

$string = "(blah blah blah) ( blah blah ) (blah)";

$result == "blah blah blah";

Which is the first portion between the first parenthesis.
 
One way is to use regular expressions:

Code:
<?php
$string = "(blah blah blah) ( bleh bleh ) (blih)";

preg_match ('@\([^\)]*\)@', $string, $result);

print trim($result[0], '()');
?>

Another is to not use regular expressions:

Code:
<?php
$string = "(blah blah blah) ( bleh bleh ) (blih)";

$first_paren = strpos ($string, '(');
$second_paren = strpos ($string, ')', $first_paren + 1);

if ($first_paren !== FALSE && $second_paren !== FALSE)
{
	$length = ($second_paren - $first_paren) - 1;
}

$result = substr ($string, $first_paren + 1, $length);

print $result;
?>



Want the best answers? Ask the best questions! TANSTAAFL!
 
awesome, i actually worked it out a bit and used the 2nd version. Thanks!
 
The second version is probably preferable. The PHP manual states its better to not use regular expressions unless you have to because regexes require a lot of server resource overhead.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top