Re: regular expression to extract from the middle of a string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ill probably get attacked viciously for this with pitchforks and machetes,
but I get sick and tired of trying to figure out regular expressions a lot
of times, so I use the following functions... getSingleMatch(),
getMultiMatch(), getSingleMatchBackwards()


function getSingleMatch($start,$end,$content) {
// finds the first match giving a beginning and a part of string that
you want to grab

// eg: to get the title from an html document, you would just use the
command getSingleMatch('<title>','</title>',$html);


$exp = explode($start,$content);
$exp2 = explode($end,$exp[1]);

return $exp2[0];
}


function getMultiMatch($start,$end,$content) {
// finds all the non-embeded matches based on a beginning and ending string
// eg: to get all the h1 tags in an html document, you would use
getMultiMatch('<h1>','</h1>',$html);

$exp = explode($start,$content);
foreach($exp as $pi) {

if(stristr($pi,$end)) {
$ex2 = explode($end,$pi);
$matches[] = $ex2[0];


}


}

return $matches;

}

function getSingleMatchBackwards($start,$end,$content) {
// the same as getSingleMatch except it goes backwards to forwards. This
helps in cases where the
// most distinct delimiter is at the end of your target rather than the
beginning.

$exp = explode($end,$content);
$exp2 = explode($start,$exp[0]);


return $exp2[count($exp2)-1];

}






On 7/14/06, Kim Christensen <kim.christensen@xxxxxxxxx> wrote:

On 7/14/06, Steve Turnbull <steve.turnbull@xxxxxxxxx> wrote:
> I have a string similar to the following;
>
> cn=emailadmin,ou=services,dc=domain,dc=net
>
> I want to extract whatever falls between the 'cn=' and the following
> comma - in this case 'emailadmin'.


$pattern= "/[^=]+=([^,]+)/";
preg_match($pattern, $string, $matches);
print_r($matches);

Voila! (Untested for now, I'm pretty drunk so sorry if it ain't workin
out like you want to)

--
Kim Christensen

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux