6

我想将网页转换为 leet (1337) 与 XPath 和 PHP 对话。

它可以只用 PHP 完成,但 HTML 节点也被替换为 leet speak。

示例($html 是网页):

$find = array("a","b","c","d","e","f","g","h","i","j"."k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
$repl = array("4","b","c","d","3","f","g","h","1","j","k","1","m","n","0","p","9","r","5","7","u","v","w","x","y","2");
$html = str_replace($find, $repl, $html);

这也替换了 HTML 节点。

这可以通过 XPath 选择器text()使用 XPath 和 PHP 来完成吗?示例($html 是网页):

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$xpath->query('//text()');
\\HERE THE REPLACING IN XPATH
4

1 回答 1

3

试试这个:

$dom = new DOMDocument;
$dom->loadHTML( $html );
$xpath = new DOMXPath( $dom );
$nodes = $xpath->query( '//text()' );
foreach( $nodes as $node )
{
    $node->nodeValue = str_replace( $find, $repl, $node->nodeValue );
}
echo $dom->saveHTML();

请注意,这可能是满足您需求的更有用的 xpath 查询:

$nodes = $xpath->query( '//head/title/text() | //body//text()' );

...因为这只会替换文本中的文本<head><title>或文本是<body>. 可能不想替换可能的样式,Javascript 和你有什么。;-)


附带说明:我已经使用您的查找和替换字符数组对此进行了测试,但是它们发生了一些可疑的事情,我无法弄清楚。替换字符似乎并不总是与找到的字符对齐。我不知道为什么会这样。

我重新创建了数组,这些对我有用:

$find = array('a','b','c','d','e','f','g','h','i','j'.'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$repl = array('4','b','c','d','3','f','g','h','1','j'.'k','1','m','n','0','p','9','r','5','7','u','v','w','x','y','2');

我只是不明白为什么你的阵列适合我。:-/ 也许是编码问题?如果有人想插话并冒险猜测,请做。

编辑:正如 rxdazn 所注意到的,"j"."k"是第一个数组中的问题,正如您从我重新创建的数组中看到的那样,我完全忽略了它(我将 $find 复制到 $repl,替换了引号,并填充了 leet 字符)。

于 2012-11-23T16:04:18.980 回答