Regular Expression Query

Hi,

I have a string in my program which can contain all parts of an address. If
any part of the address is missing, it still puts in the trailing comma - so
an address can look like

The Big House, Long Lane,,,London,,E1C 1VA

I want to run a regular expression on this to strip out the duplicate
commas. Visiting http://www.design215.com/toolbox/regexp.php, I worked out
that the expression I want is

/(,){2,}/g,", "

('worked it out' = it works on the tester on that site!)

I want to use this expression in code, and have tried

$longstring = "The Big House, Long Lane,,,London,,E1C 1VA"
$pattern = '/(,){2,}/g,", "';
ereg($pattern, $longstring, $shortstring);
echo "[".$shortstring[0]."]";

But nothing is displayed.

Can anyone point out where I'm going wrong?

Regards,

Pete.
P [ Di, 30 Januar 2007 02:44 ] [ ID #1613088 ]

Re: Regular Expression Query

P <mailnotanswered [at] nomailrequired.co.uk> wrote:

> Hi,
>
> I have a string in my program which can contain all parts of an addres=
s. =

> If
> any part of the address is missing, it still puts in the trailing comm=
a =

> - so
> an address can look like
>
> The Big House, Long Lane,,,London,,E1C 1VA
>
> I want to run a regular expression on this to strip out the duplicate
> commas. Visiting http://www.design215.com/toolbox/regexp.php, I worked=
=

> out
> that the expression I want is
>
> /(,){2,}/g,", "
> ('worked it out' =3D it works on the tester on that site!)
>
> I want to use this expression in code, and have tried
>
> $longstring =3D "The Big House, Long Lane,,,London,,E1C 1VA"
> $pattern =3D '/(,){2,}/g,", "';
> ereg($pattern, $longstring, $shortstring);
> echo "[".$shortstring[0]."]";
>
> But nothing is displayed.
>
> Can anyone point out where I'm going wrong?

Hmmz, I'd use PCRE:

$shortstring =3D preg_replace('/,+/',', ',$longstring);

-- =

Rik Wasmus
* I'm testing several new newsreaders at the moment. Please excuse =

possible errors and weird content. *
Rik [ Di, 30 Januar 2007 06:43 ] [ ID #1613090 ]

Re: Regular Expression Query

Rik wrote:
> Hmmz, I'd use PCRE:
>
> $shortstring = preg_replace('/,+/',', ',$longstring);

Many thanks Rik - worked perfectly!

Regards,

Pete.
P [ Di, 30 Januar 2007 10:07 ] [ ID #1613095 ]
PHP » alt.php » Regular Expression Query

Vorheriges Thema: Date comparison issue
Nächstes Thema: difference between two date in seconds: problem with daylight saving time