什么是这个Perl脚本的PHP等价物?

时间:2011-05-26 12:26:02

标签: php perl code-generation bookmarklet

一些解释here。这是用于将任意javascript代码转换为适合于bookmarklet的代码。

#!/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;         # 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`;

1 个答案:

答案 0 :(得分:4)

我不会为你翻译成PHP,但我会给出伪代码。

  • 将文件读入$ src string
  • 如果正则表达式与bookmarklet评论模式匹配,则删除第一行
  • 将字符串复制到另一个$ var
  • 替换任何问题模式。 PHP preg_replace()是合适的
  • 确保$ var是utf编码并正确引用,特别注意十六进制字符
  • 使用'javascript:'
  • 预先添加$ var
  • echo“// $ var \ n $ src”
  • 将$ var传递给pbcopy程序的系统调用