当前位置: 首页 > 知识库问答 >
问题:

在数组上使用时发生PHP preg_replace错误

子车灿
2023-03-14

我们有一个网络应用程序,它用str_replace()替换一些文本。查找字符串和替换字符串存储在模板文件中。

我们需要将str_replace()函数替换为preg_replace(),以便能够在find字符串中使用regex(在同一模板文件中设置它们)。

在原始脚本中,我们有这样的php代码部分。

在一个文件中:

类SiteConfig{

// Strings to search for in HTML before processing begins (used with $replace_string)
public $find_string = array();
// Strings to replace those found in $find_string before HTML processing begins
public $replace_string = array();

// a lot of code goes here

public function append(SiteConfig $newconfig) {
    foreach (array('find_string', 'replace_string') as $var) {
        // append array elements for this config variable from $newconfig to this config
        //$this->$var = $this->$var + $newconfig->$var;
        $this->$var = array_merge($this->$var, $newconfig->$var);
    }
}

// a lot of code goes here

public static function build_from_array(array $lines) {
    $config = new SiteConfig();
    foreach ($lines as $line) {
        $line = trim($line);

        // skip comments, empty lines
        if ($line == '' || $line[0] == '#') continue;

        // get command
        $command = explode(':', $line, 2);
        // if there's no colon ':', skip this line
        if (count($command) != 2) continue;
        $val = trim($command[1]);
        $command = trim($command[0]);
        //if ($command == '' || $val == '') continue;
        // $val can be empty, e.g. replace_string: 
        if ($command == '') continue;

        // strip_attr is now an alias for strip.
        // In FTR 3.8 we can strip attributes from elements, not only the elements themselves
        // e.g. strip: //img/@srcset (removes srcset attribute from all img elements)
        // but for backward compatibility (to avoid errors with new config files + old version of FTR)
        // we've introduced strip_attr and we'll recommend using that in our public site config rep.
        // strip_attr: //img/@srcset
        if ($command == 'strip_attr') $command = 'strip';

        // check for commands where we accept multiple statements
        if (in_array($command, array('title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_in_feed', 'next_page_link', 'native_ad_clue', 'http_header', 'test_url', 'find_string', 'replace_string'))) {
            array_push($config->$command, $val);
        // check for single statement commands that evaluate to true or false
        } elseif (in_array($command, array('tidy', 'prune', 'autodetect_on_failure', 'insert_detected_image'))) {
            $config->$command = ($val == 'yes');
        // check for single statement commands stored as strings
        } elseif (in_array($command, array('parser'))) {
            $config->$command = $val;
        // special treatment for test_contains
        } elseif (in_array($command, array('test_contains'))) {
            $config->add_test_contains($val);
        // special treatment for if_page_contains
        } elseif (in_array($command, array('if_page_contains'))) {
            $config->add_if_page_contains_condition($val);
        // check for replace_string(find): replace
        } elseif ((substr($command, -1) == ')') && preg_match('!^([a-z0-9_]+)\((.*?)\)$!i', $command, $match)) {
            if (in_array($match[1], array('replace_string'))) {
                array_push($config->find_string, $match[2]);
                array_push($config->replace_string, $val);
            } elseif (in_array($match[1], array('http_header'))) {
                $_header = strtolower(trim($match[2]));
                $config->http_header[$_header] = $val;
            }
        }
    }
    return $config;
}

}

在另一个文件中:

public function process($html, $url, $smart_tidy=true) {

    // a lot of code goes before

    // do string replacements
    if (!empty($this->config->find_string)) {
        if (count($this->config->find_string) == count($this->config->replace_string)) {
            $html = str_replace($this->config->find_string, $this->config->replace_string, $html, $_count);
            $this->debug("Strings replaced: $_count (find_string and/or replace_string)");
        } else {
            $this->debug('Skipped string replacement - incorrect number of find-replace strings in site config');
        }
        unset($_count);
    }

    // a lot of code goes after
}

我试图用preg_replace替换str_replace(),但在测试时显示错误:

警告:preg_replace():没有结尾匹配分隔符

            $html = preg_replace($this->config->find_string, $this->config->replace_string, $html, $_count);

错误在哪里?如何将str_replace()函数正确替换为preg_replace()?我对php非常了解,所以非常需要任何帮助。非常感谢!

共有1个答案

井誉
2023-03-14

像这样重写过程函数:

public function process($html, $url, $smart_tidy=true) {

    // a lot of code goes before

    // do string replacements
    if (!empty($this->config->find_string)) {
        if (count($this->config->find_string) == count($this->config->replace_string)) {



    $new_config_find_string = array_map(function($new_pattern)
    {
        return '/'.preg_quote($new_pattern).'/';
    },$this->config->find_string);


    $html = preg_replace($new_config_find_string, $this->config->replace_string, $html, $_count);

            $this->debug("Strings replaced: $_count (find_string and/or replace_string)");
        } else {
            $this->debug('Skipped string replacement - incorrect number of find-replace strings in site config');
        }
        unset($_count);
    }

    // a lot of code goes after
}
 类似资料:
  • 问题内容: 我正在尝试为在线Java课程创建程序。该程序包括Employee类和Name类。我必须创建多个Employee对象,并提示用户输入员工的姓名。我将所有Employee对象存储在一个employee数组中。 这是代码: 问题是编译器在运行程序时说最后一行是NullPointerException。我不确定自己在做什么错。有什么建议? 谢谢!-西恩 问题答案: 您创建了一个大小为的新数组,

  • 我有一个具有这种模式的JSON文件: 家庭电话号码数组有时可能为空。 我的spark应用程序收到这些JSON的列表,并执行以下操作: 当“home”数组为空时,我在尝试爆炸它时收到以下错误: 组织。阿帕奇。火花sql。AnalysisException:由于数据类型不匹配,无法解析“[“home]”:参数2需要整数类型,但“home”是字符串类型。;; 如果这个场是空的或是空的,有没有一种优雅的方

  • 我的系统由一个角度应用程序组成,该应用程序与Spring启动应用程序中的 REST endpoint (POST) 进行通信。Spring启动配置为使用码头作为嵌入式服务器。角度应用程序具有调用 REST 终结点并将 json 对象作为负载发送的 TypeScript 代码。json 对象的大小将从 1 MB 到 10 MB 不等,具体取决于用户在浏览器中的选择。我的Spring启动应用程序在运行

  • 问题内容: 我正在尝试将此JPA QL转换为条件构建器。JBoss 6.0。 我根据一些教程编写了此代码。 但是,我在一行中遇到了一个编译错误: 错误是: 问题答案: 好吧,我终于找到了调用gt()方法的正确方法。这是完整的解决方案。在JBoss 6中经过全面测试。

  • 我是的新手,遇到以下错误。 运行以下代码时会出现此错误(可在GitHub中获得:https://github.com/ddraj/hbase-trunk-mttr/blob/master/hbase-examples/src/main/java/org/apache/hadoop/hbase/mapreduce/sampleuploader.java) 我正在使用CDH5.2.6 我可以像这样获得

  • 我使用以下代码按Id清除文本字段(在python 2.7中使用Selenium): StaleElementReferenceException Traceback(最近一次调用last)in()StaleElementReferenceException:消息:stale element reference:元素未附加到页面文档(会话信息:chrome=65.0.3325.181)(驱动程序信息