php - preg_replace_callback 错误中的正则表达式。 PHP

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

我正在尝试创建一个网络应用程序,它将任何选定的网页转换为简单的英语形式。我有一个逐字翻译存储在 MySQL 数据库中。到目前为止我有这个代码。它有效,但似乎只能在几个标签中完成我想要的操作,而不是整个页面。我认为这可能是由于正则表达式错误造成的?

<?
    $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;
    ?>

最佳答案

您可以使用 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();

关于php - preg_replace_callback 错误中的正则表达式。 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179806/

相关文章:

php - 如何从多个表中获取数据

java - 我如何从android中的应用程序发送阿拉伯语单词并在阿拉伯语的mysql数据库上恢复?

mysql - 调整 MySQL 配置以支持锁定同一表的数百个连接

php - RegEx - 如何提取价格?

Matcher.Find() 上的 Java 正则表达式 NPE

php - 同时安装Composer依赖项

php - 如何调试 exec() 问题?

regex - 当字符串中的元素可以包含分隔符时,根据分隔符拆分字符串

php - 使用 2 个表 PhP 的管理员用户登录

mysql - 列 'PostedVoucher.stat_flag' 在选择列表中无效,因为它未包含在聚合函数或 GROUP BY 子句中