我将一个PHP字符串传递到维基百科搜索页面,以便检索部分定义。除了出现在''u形式。这里有一个例子可以更好地解释我自己。正如你所看到的,这个名字的拼音是不可读的:
亨里克·易卜生(《滑雪》,1828年3月20日-奥斯陆,1906年3月23日),戏剧,北欧诗人。
我用来从维基百科中获取片段的代码是这样的:
$word = $_GET["word"];
$html = file_get_contents('https://it.wikipedia.org/w/api.php?action=opensearch&search='.$word);
$utf8html = html_entity_decode(preg_replace("/U'+([0-9A-F]{4})/", "&#x''1;", $html), ENT_NOQUOTES, 'UTF-8');
我的代码的最后一行并不能解决问题。你知道如何获得完全可读的干净文本吗?
维基百科搜索API的输出是JSON。不要试图从中刮出一些片段,然后解析字符串的字面意思,这就是疯狂所在。只需使用一个现成的JSON解析器。
此外,当您将单词添加到查询字符串中时,您需要对其进行URL转义,否则任何在中搜索具有URL特殊字符的单词的操作都将失败。
总结:
$word = $_GET['word'];
$url = 'https://it.wikipedia.org/w/api.php?action=opensearch&search='.urlencode($word);
$response = json_decode(file_get_contents($url));
$matching_titles_array = $response[1];
$matching_summaries_array = $response[2];
$matching_urls = $response[3];
...etc...
您的正则表达式字符串中有一些错误,请尝试使用:
<?php
$str = "Henrik Ibsen, Henrik Ibsen 'u02c8h'u025bn'u027eik 'u02c8ips'u0259n(Skien, 20 marzo 1828 - Oslo, 23 maggio 1906) è stato uno scrittore, drammaturgo, poeta e regista teatrale norvegese.";
$utf8html = preg_replace('@'''U([0-9A-F]{4})@i', "&#x''1", $str);
echo $utf8html;
好吧,bobince发布的答案肯定比我之前的程序更有效,我之前的过程旨在一点一点地刮除和修剪我需要的东西。只是为了向你展示我是如何做到的,这是我以前的代码:
$html = file_get_contents('https://it.wikipedia.org/w/api.php?action=opensearch&search='.$s);
$decoded = preg_replace('@'''U([0-9A-F]{4})@i', "&#x''1", $html);
$par = array("[", "]");
$def_no_par = str_replace($par, "", $decoded);
$def_no_vir = str_replace("'"'",", "", $def_no_par);
$def_cap = str_replace("'",", "'",<br>", $def_no_vir);
$def_pulita = str_replace("'"", "", $def_cap);
$def_clean = str_replace(".,", ".", $def_pulita);
$definizione = str_replace("$s,", "", $def_clean);
$out = str_replace("''", "'"", $definizione);
正如您所看到的,删除部分输出以使其更具可读性是非常令人厌烦的(而且并不完全成功)。使用JSON方法使一切都更加线性。这是我的新解决方法:
$search = 'https://it.wikipedia.org/w/api.php?action=opensearch&search='.urlencode($s);
$response = json_decode(file_get_contents($search));
$matching_titles_array = $response[1];
$matching_summaries_array = $response[2];
$matching_urls = $response[3];
echo '<h3><div align="center"><font color=" #A3A375">'.$titolo.'</font></div></h3><br><br>';
foreach($response[1] as $t) {
echo '<font color="#5C85D6"><b>'.$t.'</b></font><br><br>';
}
foreach($response[2] as $s) {
echo $s.'<br><br>';
}
foreach($response[3] as $l) {
$link = preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1" target="_blank">$1</a>', $l);
echo $link.'<br><br>';
}
优点是现在我可以随心所欲地操作数组。你可以在这里看到它的作用: