One thing that's always bothered me about PHP is it's lack of a qq style operator. For example, in Perl, I could do something like this:
print qq/a $fun "string" with "double quotes"/;
In PHP it'd be something gross like:
print "a $fun \"string\" with \"double quotes\"";
Anyway, I found a nice solution that's been right under my nose all this time:
printf('a %s "string" with "double quotes"', $fun);
This is quite a bit cleaner for things like hyperlinks, so I thought I'd pass it along.
Ruby borrows quite a few ideas from Perl, and has a very nice %Q operator:
print %Q/a #{fun} "string" with "double quotes"/
going even further, you can use %r for regexp:
mystring =~ %r{/usr/src/linux} # no leaning toothpick required
or in Perl:
$mystring =~ m#/usr/src/linux#
Thursday, June 5, 2008
Subscribe to:
Post Comments (Atom)
4 comments:
You've given examples with print statements. What if I wanted to assign a string with complicated nested quotes to a variable? E.g., is this the best I could do in PHP?
$var = "a $fun \"string\" with \"double quotes\"";
In Perl that'd just be
my $var = qq{a $fun "string" with "double quotes"};
I know no PHP but do know a great deal of Perl, so forgive me if this question is newbieish.
Steve, the equivalent of what travis is doing to print can be accomplished with the similarly named sprintf.
i.e.
printf('a %s "string" with "double quotes"', $fun);
simply becomes
$string = sprintf('a %s "string" with "double quotes"', $fun);
I'm only familiar with these because they are borrowed straight from C.
Another not terribly elegant way of doing this is using heredoc:
$the = 'the';
$var = <<<TACOS
"I like to 'use' all kinds " of quotes all " over" ' $the ' place
TACOS;
The main caveat is that your terminator must be in the first column in order to register. So much for whitespace having no meaning.
Yup, like Jay said, sprintf would accomplish it. For having a million and one things "out of the box", PHP really falls short in certain areas. Stay tuned for an eventual all-encompassing PHP rant covering a lot of these shortcomings.
Post a Comment