好的,這是一個使用下列特殊字元擴充 XPath 語法的函式
~ 如果定義了,則插入預設命名空間前綴詞
# text() 的簡寫
% comment() 的簡寫
$ node() 的簡寫
?* processing-instruction() 的簡寫
?foo processing-instruction("foo") 的簡寫
? processing-instruction("") 的簡寫
^ 跳脫後面的字元(必要時使用文字或 SGML 實體)
以上所有內容(除了 ^)在引號字串內都會被忽略
<?php
function extendXPath($str, $defns = NULL) {
$quote = false;
$map = array(
'~' => isset($defns) ? "$defns:" : '',
'#' => 'text()',
'%' => 'comment()',
'$' => 'node()'
);
$out = '';
for ($i = 0, $len = strlen($str); $i < $len; $i++) {
$c = $str[$i];
if (!$quote && array_key_exists($c, $map)) {
$out .= $map[$c];
} else switch ($c) {
case '^':
$out .= htmlspecialchars($str[++$i], ENT_QUOTES);
break;
case '?':
if ($quote) {
$out .= $c;
} elseif ($str[$i + 1] == '*') {
$out .= 'processing-instruction()';
$i++;
} else {
preg_match('/^\w+/', substr($str, $i + 1), $matches);
$out .= 'processing-instruction("'.$matches[0].'")';
$i += strlen($matches[0]);
};
break;
case '"':
$quote = !$quote;
default:
$out .= $c;
};
};
return $out;
}
?>