开发者

What is the PHP equivalent of this Perl script?

Some explanation here. This is for converting arbitrary javascript code to code suitable for bookmarklets.

#!/usr/bin/env perl
#
# http://daringfireball.net/2007/03/javascript_bookmarklet_builder
# Licence: http://www.opensource.org/licenses/mit-license.php

use strict;
use warnings;
use URI::Escape qw(uri_escape_utf8);
use open  IO  => ":utf8",       # UTF8 by default
          ":std";               # Apply to STDIN/STDOUT/STDERR

my $src = do { local $/; <> };

# Zap the first line if there's already a bookmarklet comment:
$src =~ s{^// ?javascript:.+\n}{};
my $bookmarklet = $src;

for ($bookmarklet) {
    s{^\s*//.+\n}{}gm;  # Kill comments.
    s{\t}{ }gm;开发者_Go百科         # Tabs to spaces
    s{[ ]{2,}}{ }gm;    # Space runs to one space
    s{^\s+}{}gm;        # Kill line-leading whitespace
    s{\s+$}{}gm;        # Kill line-ending whitespace
    s{\n}{}gm;          # Kill newlines
}

# Escape single- and double-quotes, spaces, control chars, unicode:
$bookmarklet = "javascript:" .
    uri_escape_utf8($bookmarklet, qq('" \x00-\x1f\x7f-\xff));

print "// $bookmarklet\n" . $src;

# Put bookmarklet on clipboard:
`/bin/echo -n '$bookmarklet' | /usr/bin/pbcopy`;


I'm not translating it into PHP for you, but I'll give the pseudocode.

  • read the file into $src string
  • remove first line if regular expression matches bookmarklet comment pattern
  • copy string into another $var
  • substitute any problem patterns. PHPs preg_replace() would be appropriate
  • make sure $var is utf encoded and properly quoted, specifically paying attention to hex characters
  • prepend $var with 'javascript:'
  • echo "// $var\n$src"
  • system call which pipes $var to the pbcopy program
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜