Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks;
I am having a problem trying to format a url. The last part of my url will be names with spaces between them. Example, if the last name of my url looks like something like:
Inn House Company and Services, my url will end like this "http://my.test.com?infor=info2&company_name=Inn" everything after the first word because is followed by space will not be part of the url. What I am trying to do is to replace all the spaces coming from a variable $company_name per example, that has spaces in it to %20, but some how I am still not able to make one that would take any name format.
I am wondering is there is a better way to say:
I any company name has any spaces between them replace the spaces with %20, here is my regular expression, but as you can see it is not efficient as it should be.
if ($company_name=~s/(\w\&\w|\w*)(\s?)(\w*)(\s?)(\w*|\w\.)(\s?)(.*)$/$ +1%20$3%20$5%20$7/) .....

And I do have names like:
Soft, Inc. LTD
Y.O.U Co. and Services
General Help Company

It can also make the reg. exp. even more difficulty to match.
Thanks for the help.

20040409 Edit by BazB: Changed title from 'Regular Expression'

Replies are listed 'Best First'.
Re: Encoding a URL with regular expressions?
by Mr. Muskrat (Canon) on Apr 09, 2004 at 13:29 UTC

    Why use a regex at all?

    #!/usr/bin/perl use strict; use warnings; use URI::URL; use URI::Escape; # added my $company_name = 'Inn House Company Services'; $company_name = uri_escape($company_name); # added my $partial_url = 'http://my.test.com?infor=info2&company_name=' . $co +mpany_name; my $url = URI::URL->new($partial_url); print $url, "\n";

    Update: Added the two additional lines because $company_name might include other characters that need encoding. For example: 'Parker & Sons' and 'Giving 110%' both contain characters that are reserved. What if $company_name includes Unicode characters?. (URI::Escape appears to simply drop Unicode character.)

Re: Encoding a URL with regular expressions?
by gjb (Vicar) on Apr 09, 2004 at 13:20 UTC

    Why not simply $company_name =~ s/ /%20/g;

    Hope this helps, -gjb-

      Why complicate when you can simplify it, thanks, what was I thinking... it helped.....
      Thank you very much!