[thelist] php pattern matching

Matt Warden mwarden at gmail.com
Sun Feb 13 13:12:04 CST 2011


On Sun, Feb 13, 2011 at 12:16 PM, Anthony Baratta <anthony at baratta.com> wrote:
> On 2/13/2011 9:39 AM, Bob Meetin wrote:
>>
>> {12345|tom smith|whatever title} oh what a beautiful morning, yadda yadda
>
> RegEx
>
> ^{(.*)}(.*)$
>
> When you check the Matches object, you should have
>
> $1 :: 12345|tom smith|whatever title
>
> $2 :: oh what a beautiful morning, yadda yadda
>
> This assumes you don't have any returns/line feeds in your "text" area.
>
> e.g.
>
> <?php
> $ptn = "/^{(.*)}(.*)$/";
> $str = "{12345|tom smith|whatever title} oh what a beautiful morning, yadda
> yadda ";
> preg_match($ptn, $str, $matches);
> print_r($matches);
> ?>
>
> Array
> (
>    [0] => {12345|tom smith|whatever title} oh what a beautiful morning,
> yadda yadda
>    [1] => 12345|tom smith|whatever title
>    [2] =>  oh what a beautiful morning, yadda yadda
> )

Anthony, small tweak. I think you might run into trouble if the
descriptive text ever contains a } character. If you look back at the
regex:

$ptn = "/^{(.*)}(.*)$/";

We're saying: find a { as the first char. Then find any number of any
char. This (.*) sequence would actually also match }. Then you're
saying, match a } followed by any number of any char.

I think the pattern you really want is:

$ptn = "/^{([^}]+)}(.*)$/";

This is saying: find a { as the first char. Then find one or more of
any char except }. Then match a } followed by any number of any char.


-- 
Matt Warden
Austin, TX, USA
http://mattwarden.com


This email proudly and graciously contributes to entropy.


More information about the thelist mailing list