【发布时间】:2013-12-09 09:30:18
【问题描述】:
我正在尝试创建一个 Web 应用程序,它将任何选定的网页转换为简单的英语形式。我有一个单词翻译存储在 My_SQL 数据库中。到目前为止我有这个代码。它有效,但似乎只在几个标签而不是整个页面中做我想要的。我认为这可能是由于正则表达式错误?
<?
$English = array();
$Simple = array();
$con = mysqli_connect("localhost","root","root","Words");
$getmodels = mysqli_query($con, "SELECT * FROM Wordsweb");
while($res = mysqli_fetch_assoc($getmodels)) {
$English[] = $res['English'];
$Simple[] = $res['Simple'];
}
$url = $_GET['url'];
$string = file_get_contents($url);
$text_to_echo = preg_replace_callback(
"/(<([^.]+)>)([^<]+)(<\\/\\2>)/s",
function($matches) use ($English, $Simple) {
/*
* Indexes of array:
* 0 - full tag
* 1 - open tag, for example <h1>
* 2 - tag name h1
* 3 - content
* 4 - closing tag
*/
$matches[3] = strtolower($matches[3]);
$text = str_replace($English, $Simple, $matches[3]);
return $matches[1].$text.$matches[4];
},
$string
);
echo "<base href=\"" . $url . "/\" />";
echo $text_to_echo;
?>
【问题讨论】:
-
这部分正则表达式:
(<([^.]+)>)应该是开始标签,不会给你所期望的。[^.]+特别会匹配一个或多个不是点的东西,所以它会匹配比单个标签内容更多的东西。同样一般来说,您不应该使用正则表达式来解析 URL。改用 DOM php.net/DOM -
我会,但我不知道如何在其中实现 dom!
-
你应该把这个
/(<([^.]+)>)([^<]+)(<\\/\\2>)/s改成这个/(<\\s*([^<>]+?)\\s*>)([^<]+)(<\\/\\2\\s*>)/,并且你不需要在你的正则表达式中使用//s修饰符,因为类中的点只是一个文字点。 -
我会尝试使用simplehtmldom.sourceforge.net。我是否正确假设 * 意味着所有标签
标签: php mysql regex str-replace preg-replace-callback