【问题标题】:Regex in preg_replace_callback error. PHPpreg_replace_callback 错误中的正则表达式。 PHP
【发布时间】: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;
    ?>

【问题讨论】:

  • 这部分正则表达式:(&lt;([^.]+)&gt;) 应该是开始标签,不会给你所期望的。 [^.]+ 特别会匹配一个或多个不是点的东西,所以它会匹配比单个标签内容更多的东西。同样一般来说,您不应该使用正则表达式来解析 URL。改用 DOM php.net/DOM
  • 我会,但我不知道如何在其中实现 dom!
  • 或者你可以使用simplehtmldom.sourceforge.net
  • 你应该把这个/(&lt;([^.]+)&gt;)([^&lt;]+)(&lt;\\/\\2&gt;)/s改成这个/(&lt;\\s*([^&lt;&gt;]+?)\\s*&gt;)([^&lt;]+)(&lt;\\/\\2\\s*&gt;)/,并且你不需要在你的正则表达式中使用//s修饰符,因为类中的点只是一个文字点。
  • 我会尝试使用simplehtmldom.sourceforge.net。我是否正确假设 * 意味着所有标签

标签: php mysql regex str-replace preg-replace-callback


【解决方案1】:

您可以使用 DOM+Xpath 来获取和更改 HTML 文档中的文本节点:

$html = <<<'HTML'
  <html>
    <body>
      <h1>Hello World!</h1>
      <div>
        <p>Lorem Ipsum...</p>
      </div>
    </body>
  </html>
HTML;

$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXPath($dom);

$nodes = $xpath->evaluate("//text()");
foreach ($nodes as $node) {
  $node->nodeValue = strToUpper($node->nodeValue);
}

echo $dom->saveHtml();

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 2010-12-26
    • 2012-07-15
    • 2010-11-27
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    相关资源
    最近更新 更多