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


What is the PHP equivalent of this Perl script?

这里有一些解释。这是用于将任意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`;

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

  • 将文件读取到$src字符串中
  • 如果正则表达式与bookmarklet注释模式匹配,则删除第一行
  • 将字符串复制到另一个$var中
  • 替换任何问题模式。PHP preg_replace()将是合适的
  • 确保$var经过utf编码并正确引用,特别要注意十六进制字符
  • 在$var前面加上'javascript:'
  • echo"//$var''n$src"
  • 将$var管道传输到pbcopy程序的系统调用